我的IntentService
定义如下:
<service android:name=".service.AppService" android:process=":app_process" android:icon="@mipmap/ic_launcher" />
我有WakefulBroadcastReceiver
接收一些数据,我想调用上面已经运行的服务。上面的服务总是在运行,即使它被杀死,它也会重新启动。如何将消息传递给它?
我读了以下内容:
http://www.mysamplecode.com/2011/10/android-intentservice-example-using.html
http://www.truiton.com/2014/09/android-service-broadcastreceiver-example/
http://developer.android.com/guide/components/services.html
我试图做startService
,PendingIntent
等其他事情,但似乎没有任何效果。
答案 0 :(得分:0)
首先,请记住,IntentService在不同的工作线程中工作,因为它不可能与调用它的Activity进行相互通信。这就是为什么我们主要使用它们在背景上进行同步,而不需要向用户提供反馈。但是,如果要将某些信息传递给Activity,则必须按照说法使用BroadcastReceiver,并从那里创建将“数据”发送到Activity的Intent。
回到你的问题,你必须在<application>
标签内的AndroidManifest.xml中添加服务和接收器
<service android:name=".AppService"
android:enabled="true"/>
<receiver android:name=".WakefulBroadcastReceiver" >
</receiver>
然后在你的Activity中启动这样的服务(无论何时需要它,在onCreate中,或在按钮监听器中)
IntentFilter filter = new IntentFilter(WakefulBroadcastReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
WakefulBroadcastReceiver broadcastReceiver = new WakefulBroadcastReceiver();
registerReceiver(broadcastReceiver, filter);
在您的BroadcastReceiver中,您可以覆盖onReceive()方法,如下所示:
@Override
public void onReceive(Context context, Intent intent) {
// HERE IS WHERE YOU RECEIVE THE INFORMATION FROM THE INTENTSERVICE, FROM HERE YOU CAN START AN ACTIVITY OR WHATEVER YOU AIM
Toast.makeText(context, "IntentService Broadcasting", Toast.LENGTH_SHORT).show();
}
同样在同一个BroadcastReceiver中添加标识intentfilter的变量:
public static final String ACTION_RESP = "MY_FILTER_NAME"
在你的IntentService类中,你必须覆盖onHandleIntent()方法,如下所示:
@Override
protected void onHandleIntent(Intent intent) {
String msg = intent.getStringExtra("MSG");
Intent broadcast = new Intent();
broadcast.setAction(WakefulBroadcastReceiver.ACTION_RESP);
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
broadcast.putExtra("MSG", resultTxt);
// HERE IS WHERE YOU SEND THE INFORMATION YOU LOADED TO THE APP
sendBroadcast(broadcast);
}
我在我的GitHub帐户中有一个演示项目,我使用绑定和未绑定服务以及IntentServices: https://github.com/isaacurbina/PermissionsAndServices
我希望它有所帮助。
亲切的问候!
答案 1 :(得分:0)
您可以在扩展WakefulBroadcastReceiver的类中编写此代码:
@Override
public void onReceive(Context context, Intent intent) {
Intent gcmIntent = new Intent(context, MessageService.class);
gcmIntent.putExtras(intent.getExtras());
startWakefulService(context, gcmIntent);
setResultCode(Activity.RESULT_OK);
}
在你的类中写这个扩展IntentService:
@Override
protected void onHandleIntent(Intent intent) {
Bundle bundle = intent.getExtras();
//do sth with that data
MessageReceiver.completeWakefulIntent(intent);
}