BOOT_COMPLETED broadcast를 받아 service를 동작시키려고 합니다.
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.test.MBootBroadcastReceiver" android:enabled="true" android:exported="false" >
<intent-filter android:priority="1">
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name="com.test.TestService" android:enabled="true" android:exported="true" />
MBootBroadcastReceiver.java
public class MBootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BOOT_COMPLETED:" + intent.getAction(), Toast.LENGTH_LONG).show();
Intent i = new Intent(context, TestService.class);
context.startService(i);
}
}
TestService.java
public class TestService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText("Test Service Running")
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MIN)
.setOngoing(true)
.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
startForeground(startId, notification);
return super.onStartCommand(intent, flags, startId);
}
}
코드는 위와 같습니다.
adb shell을 이용하여 adb shell am broadcast -a android.intent.action.BOOT_COMPLETED 지령을 주면 제대로 서비스가 동작되는데요, 기기를 실지 리부팅하면 동작하지 않습니다.
부탁드립니다.