标签:
获取电话管理器,设置侦听
TelephonyManager tm =(TelephonyManager) getSystemService(TELEPHONY_SERVICE); tm.listen(newMyPhoneStateListener(),PhoneStateListener.LISTEN_CALL_STATE);侦听对象的实现
classMyPhoneStateListenerextendsPhoneStateListener{ //当电话状态改变时,此方法调用@Overridepublicvoid onCallStateChanged(int state,String incomingNumber){// TODO Auto-generated method stubsuper.onCallStateChanged(state, incomingNumber);switch(state){caseTelephonyManager.CALL_STATE_IDLE://空闲if(recorder !=null){ recorder.stop(); recorder.release();}break;caseTelephonyManager.CALL_STATE_OFFHOOK://摘机if(recorder !=null){ recorder.start();}break;caseTelephonyManager.CALL_STATE_RINGING://响铃 recorder =newMediaRecorder();//单词:媒体录音机//设置声音来源 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置音频文件格式 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//3gp recorder.setOutputFile("sdcard/haha.3gp");//设置音频文件编码 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);try{ recorder.prepare();}catch(IllegalStateException e){// TODO Auto-generated catch block e.printStackTrace();}catch(IOException e){// TODO Auto-generated catch block e.printStackTrace();}break;}}}publicclassBootReceiverextendsBroadcastReceiver{@Overridepublicvoid onReceive(Context context,Intent intent){//开机自启广播,启动录音机服务,在mainactivity中也启动服务Intent it =newIntent(context,RecorderService.class); context.startService(it);}bindService
publicclassLeaderServiceextendsService{@OverridepublicIBinder onBind(Intent intent){// 返回一个Binder对象,这个对象就是中间人对象returnnewZhouMi();}classZhouMiextendsBinderimplementsPublicBusiness{publicvoidQianXian(){ banZheng();}publicvoid daMaJiang(){System.out.println("陪李处打麻将");}}publicvoid banZheng(){System.out.println("李处帮你来办证");}}publicinterfacePublicBusiness{voidQianXian();}publicclassMainActivityextendsActivity{privateIntent intent;privateMyServiceConn conn;PublicBusiness pb;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent =newIntent(this,LeaderService.class); conn =newMyServiceConn();//绑定领导服务 bindService(intent, conn, BIND_AUTO_CREATE);}publicvoid click(View v){//调用服务的办证方法 pb.QianXian();}//绑定服务时要求必须传入一个ServiceConnection实现类的对象
classMyServiceConnimplementsServiceConnection{//连接服务成功,此方法调用@Overridepublicvoid onServiceConnected(ComponentName name,IBinder service){// TODO Auto-generated method stub pb =(PublicBusiness) service;}//服务失去连接时,此方法调用@Overridepublicvoid onServiceDisconnected(ComponentName name){// TODO Auto-generated method stub}}}publicclassMyServiceextendsService{privateDownloadBinder mBinder =newDownloadBinder();classDownloadBinderextendsBinder{publicvoid startDownload(){Log.d("MyService","startDownload executed");}publicint getProgress(){Log.d("MyService","getProgress executed");return0;}}@OverridepublicIBinder onBind(Intent intent){return mBinder;}……}privateMyService.DownloadBinder downloadBinder;privateServiceConnection connection =newServiceConnection(){@Overridepublicvoid onServiceDisconnected(ComponentName name){}@Overridepublicvoid onServiceConnected(ComponentName name,IBinder service){ downloadBinder =(MyService.DownloadBinder) service; downloadBinder.startDownload(); downloadBinder.getProgress();}};@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);……bindService =(Button) findViewById(R.id.bind_service);unbindService =(Button) findViewById(R.id.unbind_service);bindService.setOnClickListener(this);unbindService.setOnClickListener(this);}publicclassMusicServiceextendsService{@OverridepublicIBinder onBind(Intent intent){// TODO Auto-generated method stubreturnnewMusicController();}//必须继承binder,才能作为中间人对象返回classMusicControllerextendsBinderimplementsMusicInterface{publicvoid play(){//不写MusicService.this就成了死循环了,自己调用自己MusicService.this.play();}publicvoid pause(){MusicService.this.pause();}}publicvoid play(){System.out.println("播放音乐");}publicvoid pause(){System.out.println("暂停播放");}}publicinterfaceMusicInterface{void play();void pause();}publicclassMainActivityextendsActivity{MusicInterface mi;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);Intent intent =newIntent(this,MusicService.class);//混合调用//为了把服务所在进程变成服务进程 startService(intent);//为了拿到中间人对象 bindService(intent,newMusicServiceConn(), BIND_AUTO_CREATE);}classMusicServiceConnimplementsServiceConnection{@Overridepublicvoid onServiceConnected(ComponentName name,IBinder service){// TODO Auto-generated method stub mi =(MusicInterface) service;}@Overridepublicvoid onServiceDisconnected(ComponentName name){// TODO Auto-generated method stub}}//开始播放按钮(an)publicvoid play(View v){ mi.play();}//暂停播放按钮publicvoid pause(View v){ mi.pause();}}publicclassMainActivityextendsActivity{privateMyserviceConn conn;PublicBusiness pb;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); conn =newMyserviceConn();}publicvoid click(View v){//启动远程服务Intent intent =newIntent(); intent.setAction("com.itheima.remote"); startService(intent);}publicvoid click2(View v){//停止远程服务Intent intent =newIntent(); intent.setAction("com.itheima.remote"); stopService(intent);}publicvoid click3(View v){Intent intent =newIntent(); intent.setAction("com.itheima.remote"); bindService(intent, conn, BIND_AUTO_CREATE);}publicvoid click4(View v){ unbindService(conn);}classMyserviceConnimplementsServiceConnection{@Overridepublicvoid onServiceConnected(ComponentName name,IBinder service){//把Ibinder中间人对象强转成publicbusiness pb =Stub.asInterface(service);}@Overridepublicvoid onServiceDisconnected(ComponentName name){// TODO Auto-generated method stub}}publicvoid click5(View v){try{ pb.qianXian();}catch(RemoteException e){// TODO Auto-generated catch block e.printStackTrace();}}}publicclassMainActivityextendsActivity{PayInterface pi;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);Intent intent =newIntent(); intent.setAction("com.itheima.pangzhi"); bindService(intent,newServiceConnection(){@Overridepublicvoid onServiceDisconnected(ComponentName name){// TODO Auto-generated method stub}@Overridepublicvoid onServiceConnected(ComponentName name,IBinder service){// 使用aidl中自动生成的方法来强转 pi =Stub.asInterface(service);}}, BIND_AUTO_CREATE);}publicvoid click(View v){//调用远程服务的支付方法try{ pi.pay();}catch(RemoteException e){// TODO Auto-generated catch block e.printStackTrace();}}}有的广播接收者,必须代码注册,清单注册无效,因为这俩个发生的太平常。因为比如屏幕解锁改变不需要
一直就是他的广播,只在发生改变时接收就行了;电量改变在运行你的程序时接收就行了
publicclassMainActivityextendsActivity{privateIntent intent;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent =newIntent(this,RegisterService.class);}publicvoid start(View v){ startService(intent);}publicvoid stop(View v){ stopService(intent);}}publicclassRegisterServiceextendsService{privateScreenReceiver receiver;@OverridepublicIBinder onBind(Intent intent){// TODO Auto-generated method stubreturnnull;}@Overridepublicvoid onCreate(){super.onCreate();//1.创建广播接收者对象 receiver =newScreenReceiver();//2.创建intent-filter对象IntentFilter filter =newIntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON);//3.注册广播接收者 registerReceiver(receiver, filter);}@Overridepublicvoid onDestroy(){super.onDestroy();//解除注册 unregisterReceiver(receiver);}}publicclassScreenReceiverextendsBroadcastReceiver{@Overridepublicvoid onReceive(Context context,Intent intent){// TODO Auto-generated method stubString action = intent.getAction();if(Intent.ACTION_SCREEN_OFF.equals(action)){System.out.println("屏幕关闭");}elseif(Intent.ACTION_SCREEN_ON.equals(action)){System.out.println("屏幕打开");}}}
//和创建通知的方法类似。只不过这次在构建出Notification对象后并没有使用NotificationManager来将通知显示出来,而是调用了startForeground()方法。这个方法接收两个参数,第一个参数是通知的id,类似于notify()方法的第一个参数,第二个参数则是构建出的Notification对象。调用startForeground()方法后就会让MyService变成一个前台服务,并在系统状态栏显示出来。现在重新运行一下程序,并点击StartService或BindService按钮,MyService就会以前台服务的模式启动了,并且在系统状态栏会显示一个通知图标,下拉状态栏后可以看到该通知的详细内容Notification notification=newNotification(R.drawable.ic_launcher,"notification comes",System.currentTimeMillis());Intent notificationIntent=newIntent(this,MainActivity.class);PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0); notification.setLatestEventInfo(this,"This is title","This iscontent", pendingIntent); startForeground(1, notification);Log.d("MyService","onCreate executed");publicclassLongRunningServiceextendsService{@OverridepublicIBinder onBind(Intent intent){returnnull;}@Overridepublicint onStartCommand(Intent intent,int flags,int startId){newThread(newRunnable(){@Overridepublicvoid run(){Log.d("LongRunningService","executed at "+newDate().toString());}}).start();AlarmManager manager =(AlarmManager) getSystemService(ALARM_SERVICE);int anHour =60*60*1000;// 这是一小时的毫秒数long triggerAtTime =SystemClock.elapsedRealtime()+ anHour;Intent i =newIntent(this,AlarmReceiver.class);PendingIntent pi =PendingIntent.getBroadcast(this,0, i,0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);returnsuper.onStartCommand(intent, flags, startId);}}publicclassAlarmReceiverextendsBroadcastReceiver{@Overridepublicvoid onReceive(Context context,Intent intent){Intent i =newIntent(context,LongRunningService.class); context.startService(i);}}publicclassMainActivityextendsActivity{@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);Intent intent =newIntent(this,LongRunningService.class); startService(intent);}}<service android:name=".LongRunningService"></service><receiver android:name=".AlarmReceiver"></receiver>publicint onStartCommand(Intent intent,int flags,int startId){returnsuper.onStartCommand(intent, flags, startId);newThread(newRunnable(){@Overridepublicvoid run(){// 处理具体的逻辑 stopSelf();}}).start}@Overridepublicvoid onDestroy(){super.onDestroy();}publicclassMyIntentServiceextendsIntentService{//服务里开启子线程//1.提供一个无参的构造函数,并且必须在其内部调用父类的有参构造函数publicMyIntentService(){super("MyIntentService");//调用父类的有参构造函数}//2.在子类中去实现onHandleIntent()这个抽象方法,在这个方法中可以去处理一些具体的逻辑,而且不用担心ANR的问题,因为这个方法已经是在子线程中运行的了。这里为了证实一下在onHandleIntent()方法中打印了当前线程的id@Overrideprotectedvoid onHandleIntent(Intent p1){// TODO: Implement this method// 打印当前线程的idLog.d("MyIntentService","Thread id is "+Thread.currentThread().getId());}//3.根据IntentService的特性,这个服务在运行结束后应该是会自动停止的,所以重写onDestroy()方法,在这里也打印了一行日志,以证实服务是不是停止掉了。publicvoid onDestroy(){super.onDestroy();Log.d("MyIntentService","onDestroy executed");}//4.加入一个用于启动MyIntentService这个服务的按钮//5.在StartIntentService按钮的点击事件里面去启动MyIntentService这个服务, 并在这里打印了一下主线程的id,稍后用于和IntentService进行比对,其实IntentService的用法和普通的服务没什么两样。//6.不要忘记,服务都是需要在AndroidManifest.xml里注册的点击Start IntentService按钮后,观察LogCat中的打印日志可以看到,不仅MyIntentService和MainActivity所在的线程id不一样,而且onDestroy()方法也得到了执行,说明MyIntentService在运行完毕后确实自动停止了。集开启线程和自动停止于一身,IntentService还是博得了不少程序员的喜爱}//这是在服务里,接收activity传递过来的数据,每次用户点击ListActivity当中的一个条目时,就会服务里的该方法@Overridepublicint onStartCommand(Intent intent,int flags,int startId){// TODO Auto-generated method stub//从Intent对象当中将Mp3Info对象取出Mp3Info mp3Info =(Mp3Info)intent.getSerializableExtra("mp3Info");//生成一个下载线程,并将Mp3Info对象作为参数传递到线程对象当中DownloadThread downloadThread =newDownloadThread(mp3Info);//启动新线程Thread thread =newThread(downloadThread); thread.start();returnsuper.onStartCommand(intent, flags, startId);}标签:
原文地址:http://www.cnblogs.com/liuyu0529/p/4912468.html