开机的情况下,android系统会发出一个boot的广播,只需要定义一个broadcastReceiver,接收这个广播,启动相应的service或者activity即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package
com.app.broadcast;
import
com.app.boot.MainActivity;
import
android.content.BroadcastReceiver;
import
android.content.Context;
import
android.content.Intent;
import
android.util.Log;
import
android.widget.Toast;
public
class
BootBroadcast
extends
BroadcastReceiver {
static
final
String action_boot =
"android.intent.action.BOOT_COMPLETED"
;
@Override
public
void
onReceive(Context context, Intent intent) {
if
(intent.getAction().equals(action_boot)) {
// 1.启动自己app里面的activity
Intent myIntent1 =
new
Intent(context, MainActivity.
class
);
myIntent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent1);
// 2.启动其他app里面的activity或者service
Intent myIntent2 = context.getPackageManager()
.getLaunchIntentForPackage(
"com.example.usageslidingmenu"
);
myIntent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent2);
}
}
}
|
androidmanifest.xml:
1
2
3
4
5
6
|
<
receiver
android:name
=
"com.app.broadcast.BootBroadcast"
>
<
intent-filter
>
<
action
android:name
=
"android.intent.action.BOOT_COMPLETED"
/>
<
category
android:name
=
"android.intent.category.HOME"
/>
</
intent-filter
>
</
receiver
>
|
添加权限:
1
|
<
uses-permission
android:name
=
"android.permission.RECEIVE_BOOT_COMPLETED"
/>
|