本人最近想写个app,但是其间需要用到开机自启以及不被杀死的功能。
在网上看到高焕堂线程以“Don't call me, I'll call you back!”来总结Android框架,真是说到点子上了。理解这句话的含义后,很多关于Android平台上某种功能实现的问题就能迎刃而解了。
使用场景:手机开机后,自动运行程序,在屏幕上显示"Hello. I started!"字样。
背景知识:当Android手机启动时,会发出一个系统广播,叫做:ACTION_BOOT_COMPLETED,它的字符串表示常量为android.intent.action.BOOT_COMPLETED。所以只要在开始时程序中捕获这个广播消息,一切就好办了。
代码如下:
1、界面代码,
package com.andy.zhu;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity
{
private Button button_test_service;
private Intent intent;
private Button button_stop;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("hello started");
setContentView(tv);
}
}
2、接受广播消息,所以新建一个类,并继承BroadcastReceiver
package com.andy.zhu;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
public class BootRestartReceiver extends BroadcastReceiver
{
private final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION));
{
Intent intent2 = new Intent(context, MainActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
Log.d("DEBUG", "开机自动服务自动启动...");
//Intent intentService = new Intent();
//intentService.setClass(context, MyService.class);
//context.startService(intentService);
}
}
}
代码都很简单。重写onReceiver方法,实现要实现的功能就行了。
3、配置menifest.xml文件
package="com.andy.zhu"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="10"
android:targetSdkVersion="10" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:persistent="true"
android:theme="@style/AppTheme" >
android:name="com.andy.zhu.MainActivity"
android:label="@string/app_name" >
android:name="com.andy.zhu.BootRestartReceiver"
>
OK,大功告成,安装到手机或者模拟器上,重启一下看看效果吧。