如果我的应用已在后台服务中运行,之后在最近的应用中关闭此应用,问题是我的应用无法在后台服务中重新启动。这个问题只在其他设备上(例如xiaomi mi4i),另一台设备可以正常运行。
- 服务
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed...", Toast.LENGTH_LONG).show();
onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
-MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stopService(View view) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:1)
小米在其安全应用程序下提供“自动启动”选项。您必须手动将此选项切换为ON。除非这样做,否则您的应用程序将无法执行任何后台任务,如果它被杀死,您将无法执行简单的后台操作,如获取推送通知,更新位置等。此选项可以重新启动服务以防万一他们在后台被杀。任何后台服务(如GCM Periodic任务,AlarmManager)都将无效,直到启用自动启动选项。
答案 1 :(得分:0)
我也面临与Mi 4i相同的问题,使用以下方式安排了警报管理器但未启动。
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
Intent intent = new Intent(this, CheckReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
am.setExact(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + 5000), pendingIntent);
答案 2 :(得分:-1)
如果不能自动启动,您可以使用Alarm Manager启动服务。
旧帖这篇文章帮助你做到How to start Service using Alarm Manager in Android?