1

我有一个广播接收器,它接收android.intent.action.DOWNLOAD_COMPLETE从 AndroidDownloadManager类完成的下载。广播接收器在 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");
    }
}

Activity 启动服务:

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);
}
}

知道为什么在活动未运行时服务会被广播杀死吗?

谢谢!!

4

1 回答 1

0

您从哪里拨打电话stopService()

Activity如果您在您的 's中拨打电话onPause()onStop()或者onDestroy()Service每次离开您的电话Activity或当您的电话Activity被系统破坏时都会停止。

从您发布的代码中,我看不到BroadcastReceiver或系统广播与您之间的任何联系。Service

于 2013-03-27T05:05:33.260 回答