android 发送前台广播,使用IntentService与BroadcastReceiver实现后台服务(Android7.0可用)...
IntentService的優點
IntentService會創建單獨的線程處理所有的Intent請求,
會處理onHandleIntent方法實現的代碼,
隱藏開發者無須處理多線程問題,
當所有請求處理完成后,IntentService會自動停止
Action的使用
Action其實就是一個字符串,可以起到一個標識的作用
BroadcastReceiver的使用
BroadcastReceiver本質是一個監聽器,有自己的進程
重寫onReceive方法即可,但是在該方法里面不要執行耗時的操作,否則會ANR
發送
創建Intent
設置Action
putExtra
send發送
接收
實現onReceive方法
在AndroidManifest內增加配置
BroadcastReceiver
其他
開機自動運行的Service
第一步
動態注冊廣播
broadcastReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.space.text2.action.MSGTEXT");
//這個Action的作用是當發送為該Action的廣播時,
該MyReceiver類的onReceive方法將會接收到并處理
registerReceiver(broadcastReceiver,intentFilter);
第二步
在Activity中添加一個UI組件,比如按鈕
為按鈕添加監聽器
在該監聽器內啟動IntentService
Intent intent = new Intent(FinsihActivity.this,TextIntentService.class);
intent.setAction("com.example.space.text2.action.MSGFINSIH");
//設置該Action以便IntentService接收到Intent,
判斷是哪個Action,如果是這個Action話,就進行相應處理
intent.putExtra("finish","這是finishactivity發送的消息");
FinsihActivity.this.startService(intent);
第三步
添加一個IntentService.java類,可以使用Android Studio的自動生成
注釋掉沒有用的代碼
但是一定要保留protected void onHandleIntent(Intent intent) 和
public TextIntentService() {
super("TextIntentService");
}
方法
在protected void onHandleIntent(Intent intent) 方法中進行后臺任務的處理即可
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_MSGFINSIH.equals(action)) {
String param1 = intent.getStringExtra("finish");
Intent intent1 = new Intent(ACTION_MSGTEXT);
//此處ACTION_MSGTEXT等于"com.example.space.text2.action.MSGTEXT",
生成包含該Action的Intent后,就可以使用sendBroadcast發送廣播了,
之后自己定義的MyReceiver類的onReceive方法將會接收到并處理
intent1.putExtra("msg",param1+",IntentService收到并且廣播了出去");
sendBroadcast(intent1);
}
}
}
第四步
在自己定義的MyReceiver類的onReceive方法將會接收到并處理收到的intent
這個自己定義的MyReceiver類最好以內部類的形式寫在使用該廣播的Activity中,
這樣就可以使用該Activity的UI組件了,
即可實現把后臺服務進程中的數據更新在UI線程中的UI組件中
//內部類
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"),
Toast.LENGTH_SHORT).show();
//throw new UnsupportedOperationException("Not yet implemented");
//注意,該句是自動生成的,
一定要注釋掉,否則程序會崩潰重啟,
無法顯示出后臺服務通過廣播改變前臺UI的效果
}
}
完整代碼
第一個是Activity
public class FinsihActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finsih);
//第一步:注冊廣播,綁定廣播和action
try
{
broadcastReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.space.text2.action.MSGTEXT");
registerReceiver(broadcastReceiver,intentFilter);
Log.i("mss","registerReceiver(broadcastReceiver,intentFilter);");
}
catch (ParcelFormatException e)
{
Log.i("mss","catch");
}
Button button = (Button)super.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//第二步:開始IntentService
try
{
Intent intent = new Intent(FinsihActivity.this,TextIntentService.class);
Log.i("mss","Intent intent = new Intent(FinsihActivity.this,TextIntentService.class)");
intent.setAction("com.example.space.text2.action.MSGFINSIH");
intent.putExtra("finish","這是finishactivity發送的消息");
FinsihActivity.this.startService(intent);
Log.i("mss","FinsihActivity.this.startService(intent);");
Toast.makeText(getApplicationContext(), "startService(intent)", Toast.LENGTH_SHORT).show();
}
catch(ParcelFormatException e)
{
Log.i("mss","catch");
}
}
});
}
//內部類
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//
Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();
// TextView textView = (TextView)FinsihActivity.super.findViewById(R.id.textView13);
// textView.setText(""+intent.getStringExtra("msg"));
//throw new UnsupportedOperationException("Not yet implemented");
}
}
}
第二個是IntentService
public class TextIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_MSGTEXT = "com.example.space.text2.action.MSGTEXT";
private static final String ACTION_MSGFINSIH = "com.example.space.text2.action.MSGFINSIH";
private static final String ACTION_BAZ = "com.example.space.text2.action.BAZ";
// TODO: Rename parameters
public TextIntentService() {
super("TextIntentService");
}
// /**
// * Starts this service to perform action Foo with the given parameters. If
// * the service is already performing a task this action will be queued.
// *
// * @see IntentService
// */
// // TODO: Customize helper method
// public static void startActionFoo(Context context, String param1, String param2) {
// Intent intent = new Intent(context, TextIntentService.class);
// intent.setAction(ACTION_MSGTEXT);
// intent.putExtra(EXTRA_PARAM1, param1);
// intent.putExtra(EXTRA_PARAM2, param2);
// context.startService(intent);
// }
//
// /**
// * Starts this service to perform action Baz with the given parameters. If
// * the service is already performing a task this action will be queued.
// *
// * @see IntentService
// */
// // TODO: Customize helper method
// public static void startActionBaz(Context context, String param1, String param2) {
// Intent intent = new Intent(context, TextIntentService.class);
// intent.setAction(ACTION_BAZ);
// intent.putExtra(EXTRA_PARAM1, param1);
// intent.putExtra(EXTRA_PARAM2, param2);
// context.startService(intent);
// }
@Override
protected void onHandleIntent(Intent intent) {
Log.i("mss","onHandleIntent");
if (intent != null) {
final String action = intent.getAction();
if (ACTION_MSGFINSIH.equals(action)) {
Log.i("mss","ACTION_MSGFINSIH.equals(action)");
String param1 = intent.getStringExtra("finish");
Log.i("mss","intent.getStringExtra(\"finish\") = "+param1);
Intent intent1 = new Intent(ACTION_MSGTEXT);
Log.i("mss","Intent intent1 = new Intent(ACTION_MSGTEXT);");
Log.i("mss",ACTION_MSGTEXT);
intent1.putExtra("msg",param1+",IntentService收到并且廣播了出去");
Log.i("mss","intent1.putExtra(\"msg\",param1+\",IntentService收到并且廣播了出去\");");
sendBroadcast(intent1);
Log.i("mss","super.sendBroadcast(intent1);");
}
}
}
// /**
// * Handle action Foo in the provided background thread with the provided
// * parameters.
// */
// private void handleActionFoo(String param1, String param2) {
// // TODO: Handle action Foo
// throw new UnsupportedOperationException("Not yet implemented");
// }
// private void handleActionFinish(String param1, String param2) {
// // TODO: Handle action Foo
// throw new UnsupportedOperationException("Not yet implemented");
// }
// /**
// * Handle action Baz in the provided background thread with the provided
// * parameters.
// */
// private void handleActionBaz(String param1, String param2) {
// // TODO: Handle action Baz
// throw new UnsupportedOperationException("Not yet implemented");
// }
}
第三個是AndroidManifest
android:name=".TextIntentService"
android:exported="false">
其中exported="false"的意思是防止其他應用訪問該Service
總結
以上是生活随笔為你收集整理的android 发送前台广播,使用IntentService与BroadcastReceiver实现后台服务(Android7.0可用)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: keil c语言 1602时钟代码,带详
- 下一篇: 使用c语言读写netcdf文件,[原][