我无法理解android有关服务的新功能。在Google文档中,oreo
之后,当应用程序在后台运行时,开发人员必须使用前台服务来启动服务。
我找到了这些描述。
'从Android O开始,如果您的应用程序处于后台运行(请检查以上三个条件),则您的应用程序可以在几分钟内创建并运行后台服务。
经过几分钟,您的应用程序将进入空闲阶段。当您的应用程序进入空闲阶段时,系统将停止所有后台服务,就像您的服务调用Service.stopSelf()
一样。”
我无法理解,即使我以START_STICKY开始服务,也不会再次开始吗?我知道如果我以START_STICKY开头,它将在kill之后完全重启。为什么我必须使用JobScheduler
来满足某些需求(位置更新等)。有人可以解释一下。我不太了解google文档。
我现在在galaxy note 8 api26
手机上对其进行测试。我在应用启动时通过startService启动服务,而在关闭应用后又重新启动。旧版本之间有什么区别
谢谢。
答案 0 :(得分:0)
ublic class MyActivity2 extends Activity {
private Intent serviceIntent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("name", "ahmet vefa saruhan");
startService(serviceIntent);
findViewById(R.id.textview).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getApplicationContext(),MyService.class));
}
});
}
}
public class MyService extends Service {
private String myaction;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MYSERVICE STATUS: "," ONSTARTCOMMAND action : " + ((intent != null && intent.getStringExtra("name") != null) ? intent.getStringExtra("name") : "yok") + " OLD ACTION : "+(myaction != null ? myaction : "yok"));
Log.d("MYTHREAD name : ",Thread.currentThread().getName());
//intent.putExtra("name","isim değişti");
myaction = (intent != null) ? intent.getAction() : null;
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MYSERVICE STATUS: "," ONCREATED");
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
@Override
public void onDestroy() {
Log.d("MYSERVICE STATUS: "," ONDESTROYED");
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d("MYSERVICE STATUS: "," onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
}