Android的服务需要始终运行(决不暂停或停止)(Android Service needs to

2019-08-18 23:20发布

我创建了一个服务,并希望直到我的手机重新启动或强制关闭始终运行此服务。 服务应该在后台运行。

创建服务的示例代码和启动服务:

启动服务:

Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);

服务:

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
        HFLAG = true;
        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO for communication return IBinder implementation
        return null;
    }
}

舱单申报:

<service
    android:name=".MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</service>

是否有可能始终运行此服务。当应用程序暂停和别的。 过了一段时间我的应用程序就会暂停和服务还去暂停或停止。 那么,如何可以在后台运行,并始终这项服务。

Answer 1:

“是否有可能永远。当应用程序暂停和其他任何运行此服务?”

是。

  1. 在服务onStartCommand方法返回START_STICKY。

     public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } 
  2. 使用startService(则将MyService),使其始终保持活跃,无论绑定的客户数量在后台启动该服务。

     Intent intent = new Intent(this, PowerMeterService.class); startService(intent); 
  3. 创建粘合剂。

     public class MyBinder extends Binder { public MyService getService() { return MyService.this; } } 
  4. 定义一个服务连接。

     private ServiceConnection m_serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { m_service = ((MyService.MyBinder)service).getService(); } public void onServiceDisconnected(ComponentName className) { m_service = null; } }; 
  5. 绑定到使用bindService服务。

      Intent intent = new Intent(this, MyService.class); bindService(intent, m_serviceConnection, BIND_AUTO_CREATE); 
  6. 为你服务,你可能想一旦被关闭的通知推出相应的活动。

     private void addNotification() { // create the notification Notification.Builder m_notificationBuilder = new Notification.Builder(this) .setContentTitle(getText(R.string.service_name)) .setContentText(getResources().getText(R.string.service_status_monitor)) .setSmallIcon(R.drawable.notification_small_icon); // create the pending intent and add to the notification Intent intent = new Intent(this, MyService.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); m_notificationBuilder.setContentIntent(pendingIntent); // send the notification m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build()); } 
  7. 您需要修改清单,推出单顶模式的活动。

      android:launchMode="singleTop" 
  8. 需要注意的是,如果系统需要的资源和你的服务不是很活跃,可能被杀死。 如果这是不可接受的把服务前台使用startForeground。

      startForeground(NOTIFICATION_ID, m_notificationBuilder.build()); 


Answer 2:

为了开始在自己的进程服务,你必须指定在XML声明如下。

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service> 

在这里你可以找到一个很好的教程,这是真的对我很有用

http://www.vogella.com/articles/AndroidServices/article.html

希望这可以帮助



Answer 3:

一个简单的解决方案是,当系统停止它重新启动该服务。

我发现这非常简单的实现这个方法的:

如何使Android服务势不可挡



Answer 4:

您可以实现startForeground的服务,即使死了,你可以通过重新启动START_STICKYstartCommand() 不知道,虽然这是正确的执行。



Answer 5:

如果你已经有了一个服务,并希望它的工作的时候,你需要添加两件事情:

  1. 在服务本身:

     public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } 
  2. 在清单:

     android:launchMode="singleTop" 

没有必要,除非你需要它的服务添加绑定。



Answer 6:

我发现保持的简单明了的方式Service运行始终。

这家伙有这么明确的解释,并已经使用了一个好的算法。 他的方法是发送一个广播时,该服务即将获得打死,然后用它来重新启动该服务。

你应该看看: http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android



Answer 7:

在清单中添加这一点。

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

添加一个服务类。

public class YourServiceName extends Service {


    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}


Answer 8:

我已经克服了这个问题,我的示例代码如下所示。

添加下面一行在你的主要活动,在这里BackGroundClass是服务class.You可以在创建这个类- > JavaClass(在这个类中,添加在您需要在后台发生的过程(任务))。 为方便起见,先用通知铃声作为后台进程表示它们。

 startService(new Intent(this, BackGroundClass .class));

在BackGroundClass,就包括我的译码,并您可能会看到的结果。

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class BackgroundService  extends Service {
    private MediaPlayer player;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
        player.setLooping(true);
         player.start();
        return START_STICKY;
    }
 @Override
    public void onDestroy() {
        super.onDestroy();
         player.stop();
    }
}

而在AndroidManifest.xml中,尝试添加此。

<service android:name=".BackgroundService"/>

运行程序,只要打开该应用程序时,您可能会发现在后台的通知提醒。 甚至,你可以退出应用程序,但你仍然可能听到铃声警报,除非和直到你关闭应用程序或卸载应用程序。 这表示该通知警告在后台进程。 这样你就可以添加背景的一些过程。

亲切关怀:请不要使用Toast验证,因为它只能运行,即使它是在后台进程一次。

希望这将帮助... !!



Answer 9:

您不需要广播接收器。 如果一个人会服用一些止痛副本API(serviceconnection)的一个例子,从上面的斯蒂芬Donecker并将其粘贴在谷歌,你会得到这个, https://www.concretepage.com/android/android-local-bound-service-例如与-粘结剂和- serviceconnection



文章来源: Android Service needs to run always (Never pause or stop)