奔跑的回忆 | 个人博客 |IT技术经验分享| irunthink.com - 本地通知
type: channel
link: https://www.irunthink.com/tag/%E6%9C%AC%E5%9C%B0%E9%80%9A%E7%9F%A5/
items: android 两个程序之间如何通过 service 来监听广播
items: 安卓开发多线程技术

android 两个程序之间如何通过 service 来监听广播
type: item
date: 2020-02-17T17:08:00+08:00
description: 一个用来发送广播同时自己也接受广播，另一个是用service来监听上一个的广播，当上一个发出广播时，给出相应。一、全局广播：发送的activity：import android.widget.Toast; public class TestActivity extends Activity { private final String ACTION_NAME = "send Message"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView t = (TextView) this.findViewById(R.id.tv_test); t.setText("send broadcast"); registerBroadcastReceiver(); t.setOnClickListener(new View.OnClickListener() {//发送广播 @Override public void onClick(View v) { Intent mIntent = new Intent(ACTION_NAME); mIntent.putExtra("message", "send broadcast"); sendBroadcast(mIntent); } }); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {//接收广播 @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); if(action.equals(ACTION_NAME)){ String tt = intent.getStringExtra("message"); // Toast.makeText(getApplicationContext(), tt, 0).show(); //取消这行可显示信息 } } }; private void registerBroadcastReceiver(){ IntentFilter mFilter = new IntentFilter(); mFilter.addAction(ACTION_NAME); registerReceiver(mBroadcastReceiver,mFilter); } @Override public void onBackPressed() {//推出取消监听广播 unregisterReceiver(mBroadcastReceiver); super.onBackPressed(); } } service 代码：import android.widget.Toast; public class MyService extends Service{ private final String ACTION_NAME = "send Message";//监听广播Intent 的名称。 @Override public void onCreate() { Toast.makeText(this, "frist create", 0).show(); registerBroadcastReciver(); System.out.println("test"); super.onCreate(); } @Override public void onDestroy() { unregisterReceiver(mBroadcastReceiver);//服 务销毁时，取消监听广播 super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { registerBroadcastReciver(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } public Broa…

安卓开发多线程技术
type: item
date: 2020-02-17T16:20:00+08:00
description: 方法一：new Thread(){ @Override public void run() { final boolean net = ping(); runOnUiThread(new Runnable() { @Override public void run() { //主线程在这调用更新UI代码 Message msg = new Message(); msg.what = 102; msg.obj = net; handler.sendMessageDelayed(msg, 0); } }); } }.start(); 方法二：new Thread(new Runnable() { @Override public void run() { ping();//耗时操作 } }).start();