我有一个广播接收器,可以从Android的android.intent.action.DOWNLOAD_COMPLETE
课程中接收下载完成DownloadManager
。广播接收器在XML中定义如下:
<receiver android:name=".DownloadReceiver" >
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
如果我保持活动正常运行,那么每件事情都会很好。但是,如果在后台运行服务时活动未运行,则每次DOWNLOAD_COMPLETE
广播进入时都会导致后台服务器被杀死。
广播接收者是:
public class DownloadReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// it will cause MyService to be killed even with an empty implementation!
}
}
服务是:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
Log.w(TAG, "onBind called");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.w(TAG, "onCreate called");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.w(TAG, "onStartCommand called");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.w(TAG, "onDestroy called");
}
}
活动启动服务:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void startService() {
Intent start = new Intent(getApplicationContext(), MyService.class);
startService(start);
}
public void stopService() {
Intent stop = new Intent(getApplicationContext(), MyService.class);
stopService(stop);
}
}
知道为什么服务在活动未运行时被广播杀死了?
谢谢!
答案 0 :(得分:0)
您从哪里拨打stopService()
?
如果您使用Activity
onPause()
,onStop()
或onDestroy()
拨打电话,则每次离开Service
时{0}都会停止{1}}或当Activity
被系统销毁时。
我发现Activity
或系统广播与您发布的代码中的BroadcastReceiver
之间没有任何关联。