我正在实现以下代码,其中我想使用广播接收器启动服务。广播接收器中的Toast工作正常,但服务没有执行。 谁能告诉我哪里出错了?
MyReceiver.class
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
//Toast.makeText(arg0, "Service", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(arg0,MyS.class);
arg0.startService(myIntent);
}
}
MyS.class
public class MyS extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.p"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<service android:enabled="true"
android:name=".MyS" >
<intent-filter>
<action android:name="com.test.p.MyS" >
</action>
</intent-filter>
</service>
<receiver android:enabled="true"
android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
答案 0 :(得分:-1)
在您的活动中,创建一个BroadcastReceiver变量
private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// start your service right here...
}
};
以及onCreate
的{{1}}或onResume
个事件,您应该注册Activity
BroadcastReceiver
和onDestory或onStop或onPause无论你处于什么状态都应取消注册此BroadcastReceiver以便不再接收此更新。
super.registerReceiver(mBootCompletedReceiver, new IntentFilter("android.intent.action.BOOT_COMPLETED"));
答案 1 :(得分:-2)
只有当有一个名为coz的onreceive方法时,服务才会启动。你已经在receive方法中给出了startservice。这意味着,你必须启动一些接收器活动,如呼叫或短信启动服务。 U可以在启动时启动服务。谷歌吧。