Service的啟動
Acitivity代碼
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_start=findViewById(R.id.Button_start);
button_stop=findViewById(R.id.Button_stop);
button_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
});
button_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(intent);
}
});
service代碼
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
Log.i("TAG","綁定");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("TAG","創(chuàng)建");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("TAG","停止");
}
}
發(fā)送廣播切換圖片
Acitivity代碼
public class Main3Activity extends AppCompatActivity {
private LocalBroadcastManager localBroadcastManager;
private MyReceiver myReceiver;
private Button button;
private ImageView imageView;
private Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
button=findViewById(R.id.Button);
imageView=findViewById(R.id.ImageView);
MyReceiver myReceiver = new MyReceiver(handler,imageView);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.shuibi");
registerReceiver(myReceiver,intentFilter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.shuibi");
sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(myReceiver);
}
}
service代碼
public class MyReceiver extends BroadcastReceiver {
private android.os.Handler handler;
private ImageView imageView;
public MyReceiver(Handler handler, ImageView imageView) {
this.handler = handler;
this.imageView = imageView;
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
Log.i("TAG","onReceive");
String action = intent.getAction();
if(action.equals("com.shuibi")){
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageResource(R.mipmap.jhg);
}
});
}
}
}