300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > android开机固定程序 Android实现开机自启动某个程序

android开机固定程序 Android实现开机自启动某个程序

时间:2022-10-17 04:50:52

相关推荐

android开机固定程序 Android实现开机自启动某个程序

本人最近想写个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、界面代码,

packagecom.andy.zhu;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.TextView;

importandroid.app.Activity;

importandroid.content.Intent;

publicclassMainActivityextendsActivity

{

privateButtonbutton_test_service;

privateIntentintent;

privateButtonbutton_stop;

@Override

protectedvoidonCreate(BundlesavedInstanceState)

{

super.onCreate(savedInstanceState);

TextViewtv=newTextView(this);

tv.setText("hellostarted");

setContentView(tv);

}

}

2、接受广播消息,所以新建一个类,并继承BroadcastReceiver

packagecom.andy.zhu;

importandroid.app.Service;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.content.pm.PackageManager;

importandroid.util.Log;

publicclassBootRestartReceiverextendsBroadcastReceiver

{

privatefinalStringACTION="android.intent.action.BOOT_COMPLETED";

@Override

publicvoidonReceive(Contextcontext,Intentintent)

{

//TODOAuto-generatedmethodstub

if(intent.getAction().equals(ACTION));

{

Intentintent2=newIntent(context,MainActivity.class);

intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent2);

Log.d("DEBUG","开机自动服务自动启动...");

//IntentintentService=newIntent();

//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,大功告成,安装到手机或者模拟器上,重启一下看看效果吧。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。