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
<service
android:name=".TextIntentService"
android:exported="false"></service>
其中exported="false"的意思是防止其他应用访问该Service
|