Android--开机自启动(activity或service)

来源:互联网 发布:安卓好用的拼长图软件 编辑:程序博客网 时间:2024/06/05 11:57

Android手机在启动的过程中会触发一个Standard Broadcast Action,名字叫android.intent.action.BOOT_COMPLETED(记得只会触发一次呀),在这里我们可以通过构建一个广播接收者来接收这个这个action。必须要注意的一点是:这个广播必须的静态注册的,不能是动态注册的广播(这种接受开机广播的,一定要静态注册,这样应用还没运行起来时也照样能够接收到开机广播  ,动态广播就不行了)。

在装上demo让demo运行后,先关机,再启动。也就是说装上应用运行后,一定要重启机器。

如果失败:看看有没有装360之类的被限制,还有手机自带的管理自启动的软件,进去点击允许;

运行方式: adb shell am startservice -n 包名/包命.TestService        //manifest中的service name

adb模拟开机:adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

1、注册开机广播,在清单文件中注册:

<receiver            android:name=".MyReceiver"            android:enabled="true"            android:exported="true">            <intent-filter android:priority="1000">                <action android:name="android.intent.action.BOOT_COMPLETED"></action>            </intent-filter></receiver>        <service android:name="com.example.openandroid.MyService">            <intent-filter >               <action android:name="com.example.openandroid.MyService" />                 <category android:name="android.intent.category.default" />            </intent-filter>        </service>

2.在开机广播的onReceive方法里面做跳转:

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyReceiver extends BroadcastReceiver{    public MyReceiver()    {    }    @Override    public void onReceive(Context context, Intent intent)    {        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))        {//            Intent i = new Intent(context, MainActivity.class);//            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//            context.startActivity(i);        Intent i = new Intent(context, MyService.class);        context.startService(i);        }    }}

3.MainActivity

mport android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Toast.makeText(this, "哈哈,我成功启动了!", Toast.LENGTH_LONG).show();        Log.e("AutoRun","哈哈,我成功启动了!");}}

4.MyService

import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);Intent i = new Intent(Intent.ACTION_MAIN);    i.addCategory(Intent.CATEGORY_LAUNCHER);                ComponentName cn = new ComponentName(packageName, className);                i.setComponent(cn);    startActivity(i);    }}


原创粉丝点击