《android开机启动service.doc》由会员分享,可在线阅读,更多相关《android开机启动service.doc(5页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、android开机启动service,适合闹钟程序 实例中一共三个类public class yourReceiver extends BroadcastReceiverpublic class ServiceTest extends Servicepublic class showActivity extends ActivityyourReceiver 类: package ; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; pu
2、blic class yourReceiver extends BroadcastReceiver Override public void onReceive(Context context, Intent intent) Intent i = new Intent(context, ServiceTest.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(i); 复制代码ServiceTest 类: package ; import java.util.Calendar; import andro
3、id.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.util.Log; public class ServiceTest extends Service Handler hd1=new Handler(); /*启动activity的开关*/ boolean b; /*启动一次activity之后的一分钟内将不再重新启动*/ int time; public static final Intent ACTION_ST
4、ART = null; private static final String TAG = TestService; Override public IBinder onBind(Intent intent) return null; Override public boolean onUnbind(Intent i) Log.e(TAG, = TestService.onUnbind); return false; Override public void onRebind(Intent i) Log.e(TAG, = TestService.onRebind); Override publ
5、ic void onCreate() Log.e(TAG, = TestService.onCreate); hd1.postDelayed(mTasks, delay); Override public void onStart(Intent intent, int startId) Log.e(TAG, = TestService.onStart); Override public void onDestroy() Log.e(TAG, = TestService.onDestroy); public void log() Calendar c= Calendar.getInstance(
6、); int h=c.getTime().getHours(); int m=c.getTime().getMinutes(); Log.i(hour, +h); Log.i(minute, +m); /*这里的16和10可以自己定义一下 主要是提醒的时间设置,我不想做的太繁琐,所有没有些闹钟,只是用这个测试一下:)*/ if(h=16&m=10) /*为防止持续调用,所以用boolean 变量b做了一个小开关*/ if(!b) Intent i = new Intent(); i.setClass(ServiceTest.this, showActivity.class); i.setFla
7、gs(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(i); this.stopSelf(); b=true; /*开关开启后计时60秒,在这60秒之内就不再重新启动activity了,而60秒一过,上面的h和m条件肯定就不成立了*/ if(b) time+=5; if(time=60) time=0; b=false; /* 速度控制参数(单位豪秒) */ private int delay = 5000; /* * 控制速度 * */ private Runnable mTasks = new Runnable() public voi
8、d run() log(); hd1.postDelayed(mTasks, delay); ; 复制代码showActivity 类:(次类中啥都没有,就是演示一下activity可以被启动) package ; import .R; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class showActivity extends Activity Override public void
9、 onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); 复制代码下面是很重要的AndroidManifest 复制代码既可以作为开机启动并隐藏到后台的service,也可以当做activity打开,可以说做东西会很方便。