即使应用程序被关闭(终止),也能运行服务。

15

我希望即使应用程序被关闭(杀死)或用户不启动应用程序,该服务也能运行。

我希望在应用程序安装后启动该服务,并从此刻起始终运行该服务。

public class notifications extends Service {

        @Override
        public IBinder onBind(Intent intent) {
                // TODO Auto-generated method stub
                return null;
        }

        @Override
    public void onCreate() {
    }

    @Override
    public void onStart(Intent intent, int startId) {
                final Handler handler = new Handler();
                final Runnable runb = new Runnable()
                {
                    public void run()
                    {
                        Toast.makeText(getApplicationContext(), " Service Started", Toast.LENGTH_LONG).show();
                        handler.postDelayed(this, 10000);
                    }
                };
                handler.postDelayed(runb, 0);

    }
    @Override
    public void onDestroy() {

    }
}*/

public class notifications extends IntentService
{
        private Timer mBackGroundTimer;
        public notifications()
    {
        super("myservice");
        this.mBackGroundTimer=new Timer();
    }
        @Override
        protected void onHandleIntent(Intent intent)
    {
        // TODO Auto-generated method stub
        mBackGroundTimer.schedule(new TimerTask()
        {
            public void run()
            {
                try
                {
                        Notification("This is message from Dipak Keshariya (Android Application Developer)", "This is Android Notification Message");
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        },1000, 2000);
    } // END onHandleIntent()
        private void mStopTimer()
    {
        //Call this whenever you need to stop the service
        mBackGroundTimer.cancel();
    }

        private void Notification(String notificationTitle, String notificationMessage) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, "A New Message from Dipak Keshariya (Android Developer)!",
            System.currentTimeMillis());

            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingIntent);
            notificationManager.notify(10001, notification);
        }
}

我该怎么做呢?


1
阅读这个网址 http://developer.android.com/reference/android/app/IntentService.html 和这个网址 http://www.vogella.com/articles/AndroidServices/article.html。 - nilkash
4个回答

11

从你的代码来看,似乎你希望你的服务周期性地提供通知。

就持续运行而言,请注意,按设计,Android系统可以随时终止你的服务进程。你可以在一定程度上影响这一点,但无法阻止系统杀死你的服务。

因此,对于你的周期性操作,最好使用AlarmManager和重复的闹钟。然后,你的服务基本上是一次性的,即执行一次操作,然后退出。

有关一些代码,请查看这里的示例:

Android:Alarm Manager


所以,我将这个代码放在我的MainActivity里面,它会启动服务,即使我关闭应用程序,该服务也不会停止运行? - tornal vergaro
它将注册一个闹钟,定期启动您的服务。您的服务不需要一直运行(实际上,在执行所需操作后,您的服务应该立即退出),因为您可以设置闹钟在需要时触发单个服务运行。您的应用程序也无需运行。 - bgse
我想在 X 添加时发送通知,但是 X 存在于一个网站上的 JSON 中。因此,我需要始终运行服务,如果 X 添加了,我就想要发送通知。而且它需要一直运行,即使我没有启动应用程序。 - tornal vergaro
4
使用闹钟管理器的方法,您的服务将不需要一直运行。当执行时,您的服务只需检查条件 X 一次,如果为真,则发送通知。闹钟管理器会负责每 x 秒调用您的服务,这实际上与始终运行服务相同。好处是,您无需担心 Android 系统终止您的服务进程,因为每次需要执行任务时,服务都会重新启动。即使您的应用程序没有运行,由于闹钟管理器不依赖于您的应用程序。 - bgse

5

您需要实现Service类的OnStartCommand方法,并在其中返回Service.START_STICKY。这样就可以解决问题了。如果您关闭应用程序,服务将继续在后台运行。但是,如果您重新启动手机,则需要在应用程序中实现其他内容,比如启动服务或类似的东西。


我认为在启动应用程序之前无法启动服务。但是使用START_STICKY后,启动服务后它不会停止。 - Hampel Előd
但我的要求是必须在应用程序启动后启动服务。例如,在登录后。 - Naimish B. Makwana

1

由于您的要求是在后台运行服务,因此使用服务是正确的选择,因为它只用于后台运行目的。

从活动中,您可以通过以下方式启动服务:

startService(new Intent(activityName.this, serviceName.class));

如果您的应用程序没有任何活动,那么您可以将服务设置为应用程序的默认和主要启动器,方法是将其放置在

标签中。

<service android:name="name of the service" >
 <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
 </service>

是的,但如果我关闭应用程序或重新启动智能手机,服务将停止工作,但我希望它始终运行。 - tornal vergaro
关闭应用程序和重启设备是两件不同的事情。您可以在手机重新启动时放置一个广播接收器,然后启动您的服务。并将您的服务设置为粘性,这样系统就不会杀死它。 - Dinesh Prajapati

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接