我不想在android 4.0.3启动时启动服务,但是当我启动设备时,它不会发生在我的设备中,服务无法启动。请帮助我,谢谢你
这是我的清单
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.android.testsharedpreference.MyService"></service>
<receiver android:name="com.android.testsharedpreference.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
我的电视广播接收器
public class BootReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
context.startService(new Intent(context,MyService.class));
}
}
}
和我的服务
public class MyService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
super.onCreate();
Toast.makeText(MyService.this, "onCreate Service ", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(MyService.this, "onDestroy Service ", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:2)
你应该在ICS之前添加add android.permission.RECEIVE_BOOT_COMPLETED
,因为应用程序工作正常但从ICS开始是你没有这个权限你的应用程序不会收到启动完成的意图
答案 1 :(得分:0)
不要忘记在MyService中覆盖“onStartCommand”方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String action = intent == null ? null : intent.getAction();
Log.d("onStartCommand", "action = " + action);
/* ... */
return START_NOT_STICKY; // for example ...
}