如果我的应用程序已经在后台服务中运行,并在此之后关闭最近的应用程序,问题是我的应用程序无法在后台服务中再次启动。这个问题只有在其他设备(例如小米mi4i)上才会出现,其他设备可以正常运行。
-Service
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);
}}
发布于 2016-08-22 16:43:07
小米在其安全应用程序下提供了“自动启动”选项。您必须手动将此选项切换为ON。除非这样做,否则你的应用程序将无法执行任何后台任务,如果它被杀死,你将无法执行简单的后台操作,如获取推送通知,更新位置等。此选项使服务能够重新启动,以防它们在后台被杀死。任何后台服务,如GCM定期任务,AlarmManager将是无用的,直到自动启动选项打开。
发布于 2015-12-29 17:31:10
对于小米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);发布于 2015-12-17 11:50:24
如果服务没有自动启动,您可以使用Alarm Manager启动服务。
以前的这篇文章可以帮你做How to start Service using Alarm Manager in Android?
https://stackoverflow.com/questions/34326166
复制相似问题