android开机自启动
原理,在收到系统开机广播后,启动一个透明的activity,在activity里面启动一个服务。
关键代码如下:
1、开机广播接受者
|
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
|
public class BootReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(android.intent.action.BOOT_COMPLETED)) { Log.d(BootReceiver, system boot completed); // context, AutoRun.class Intent newIntent = new Intent(context, AutoRun.class); /* MyActivity action defined in AndroidManifest.xml */ newIntent.setAction(android.intent.action.MAIN); /* MyActivity category defined in AndroidManifest.xml */ newIntent.addCategory(android.intent.category.LAUNCHER); /* * If activity is not launched in Activity environment, this flag is * mandatory to set */ newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); /* if you want to start a service, follow below method */ context.startActivity(newIntent); } }} |
2、开机启动的activty透明
|
1
|
|
|
1
|
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class AutoRun extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去除title requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉Activity上面的状态栏 getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); Log.i(开机启动,开机启动); startService(new Intent(this,EndClientService.class)); finish(); }} |
3、开机启动的服务
|
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
33
34
35
|
public class EndClientService extends Service { private Intent intent2=null; public EndClientService() { // TODO Auto-generated constructor stub } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.i(开机服务,服务开启); IntentFilter filter=new IntentFilter(); filter.addAction(android.provider.Telephony.SMS_RECEIVED); filter.setPriority(Integer.MAX_VALUE); registerReceiver(mReceiver, filter); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(服务,服务运行中); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); unregisterReceiver(mReceiver); mReceiver=null; } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } |
|
1
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> |
|
1
2
3
4
5
6
7
|
<receiver android:label="@string/app_name" android:name="com.yqq.endClient3.BootReceiver"> <intent-filter android:priority="1000"> <category android:name="android.intent.category.LAUNCHER"> </category></action></intent-filter> </receiver> |
推推族,免费得门票,游景区:www.tuituizu.com
结伴旅游,一个免费的交友网站:www.jieberu.com
以上内容,全部转载,如有侵权,请联系我!

浙公网安备 33010602011771号