原理,在收到系统开机广播后,启动一个透明的activity,在activity里面启动一个服务。
关键代码如下:
1、开机广播接受者
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透明
3、
</pre><pre name="code" class="java">
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、开机启动的服务
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;
}
需要配置的权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" >
<receiver
android:name="com.yqq.endClient3.BootReceiver"
android:label="@string/app_name" >
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>