2013-03-24 43 views
0

我有一台广播接收器,它接收来自Android的DownloadManager类的下载完成android.intent.action.DOWNLOAD_COMPLETE。广播接收器在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

为什么你要为同一个类创建新的意图 – Unknown 2013-03-27 05:09:38

+0

为什么你要为意图创建两个对象......只需使用第一个对象来启动和停止服务。 – Unknown 2013-03-27 05:12:38

+0

@CobraAjgar使用不同的意图来启动和停止服务不是问题的原因。 – rain 2013-04-07 01:39:49

回答

0

从哪里打电话给stopService()

如果你正在你的Activity的通话onPause()onStop()onDestroy()那么你Service停止每当你离开,你的Activity或当Activity得到由系统破坏。

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

+0

该服务是前台服务,即使活动已关闭,该服务仍会继续运行。 stopService()仅从按钮单击事件中调用。 Activity的onPause(),onStop()或onDestroy()不会影响服务。是的,DownloadReceiver根本没有连接到MyService。 MyService不处理任何广播。我现在更新了活动课的原始问题。 – rain 2013-04-07 01:47:26