android四大组件之Service 注册广播接收者
生活随笔
收集整理的這篇文章主要介紹了
android四大组件之Service 注册广播接收者
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
廣播的注冊一共有兩種,一種就是用清單文件注冊,還有另外一種就是用代碼注冊,代碼注冊比較靈活,可以在需要的時候注冊,不需要的時候解除注冊
用服務注冊廣播首先要開啟服務,
然后在服務oncreate方法里注冊廣播,在ondestory方法里解除注冊就可以了
package com.example.zhuceBroadcast;import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View;public class MyActivity extends Activity {/*** Called when the activity is first created.*/private Intent intent;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);intent = new Intent(this,RegistService.class);findViewById(R.id.startservie).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {startService(intent);}});findViewById(R.id.stopservice).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {stopService(intent);}});} } package com.example.zhuceBroadcast;import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder;/*** Created by Administrator on 2015/11/17 0017.*/ public class RegistService extends Service {MyReceiver myReceiver;@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {//拿到廣播接收者對象 myReceiver = new MyReceiver();//拿到intentfilterIntentFilter filter = new IntentFilter();//屏幕開啟和關閉 filter.addAction(Intent.ACTION_SCREEN_ON);filter.addAction(Intent.ACTION_SCREEN_OFF);//注冊 registerReceiver(myReceiver, filter);}@Overridepublic void onDestroy() {unregisterReceiver(myReceiver);} } package com.example.zhuceBroadcast;import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast;/*** Created by Administrator on 2015/11/17 0017.*/ public class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if(Intent.ACTION_SCREEN_ON.equals(action)){Toast.makeText(context,"屏幕開啟",Toast.LENGTH_LONG).show();}else if (Intent.ACTION_SCREEN_OFF.equals(action)){Toast.makeText(context,"屏幕關閉",Toast.LENGTH_LONG).show();}} }?
轉載于:https://www.cnblogs.com/84126858jmz/p/4970972.html
總結
以上是生活随笔為你收集整理的android四大组件之Service 注册广播接收者的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Swift使用CoreLocation,
- 下一篇: [J2ME]RSSOwlMidlet(R