我已经创建了一个后台服务,当我杀死应用程序时,该服务在Android 6.0以下正常运行。
同样适用于Android 6.0及更高版本,但仅限于最小化应用。
当我在Android 6.0及以上版本中杀死app时,也会杀死并且不会重启,也无法在BOOT_COMPLETE上启动。
该怎么办? 我能举个简单的例子吗?
我试过这个: 的 MyService.java
public class MyService extends Service {
private MediaPlayer player;
@Nullable
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet started");
}
public A_ExampleMyService() {
super();
}
@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 onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
MyActivity.java
public class MyActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_example_activity);
this.context = this;
Intent background = new Intent(MyActivity.this,MyService.class);
context.startService(background);
}
}
的manifest.xml
<manifest>
<application>
<service>
<android:name=".MyService">
<android:enabled="true">
<android:exported="true"/>
</application>
</manifest>