我的应用中有一项服务,用于向服务器发送http post请求,称为Communicator
。我通常从我的活动绑定它,但现在我需要从广播接收器调用它(因为我需要每分钟向服务器发送一次请求)所以我使用startService(intent)
经过一些调试后,似乎在调用startService(intent)
时出现以下错误:
08-04 06:07:10.447: W/ActivityManager(1138): Unable to start service Intent { act=ping_states flg=0x14 cmp=com.example.imhere/.Pinger (has extras) } U=0: not found
这是我的课程,扩展了BroadcastReceiver
:
public class Pinger extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//start the communicator and request to iterate over locations with true 'here state'
Log.d("tom.debug", "Pinger class is calling to start the service"); //acording to the log, this part of the code is reached
/*EDIT - THE ISSUE WAS FOUND HERE - See Imtiyaz's answer*/
context.startService(intent); //so this is probably the reason I'm seeing the error
}
}
这是我创建意图的方式(根据这里的问题:How to run a method every X seconds):
private void startPinging() {
Date when = new Date(System.currentTimeMillis() + (MINUTE));
try{
Intent pingerIntent = new Intent(this.getApplicationContext(), Pinger.class);
pingerIntent.setAction(getString(R.string.intent_action_ping_states));
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(),
0,
pingerIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) this.getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
alarms.set(AlarmManager.RTC_WAKEUP,
when.getTime(),
pendingIntent);
alarmSet = true;
Log.d("tom.debug", "startPinging: alarmSet is now true");
} catch(Exception e){
e.printStackTrace();
}
}
我认为清单文件也是相关的:
...
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:enabled="true"
android:exported="false"
android:name="com.example.imhere.Pinger" >
<intent-filter>
<action android:name="@string/intent_action_ping_states" />
</intent-filter>
</receiver>
<service
android:name="com.example.imhere.Communicator"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="@string/intent_action_ping_states" />
</intent-filter>
</service>
...
</application>
...
答案 0 :(得分:3)
你不能像你一样直接启动意图。
以这种方式尝试:
@Override
public void onReceive(Context context, Intent intent) {
//start the communicator and request to iterate over locations with true 'here state'
Log.d("tom.debug", "Pinger class is calling to start the service"); //acording to the log, //this part of the code is reached
//context.startService(intent); //so this is probably the reason I'm seeing the error
//if some data you want from this broadcast event then you can do like
// String tempMessage = intent.getStringExtra("KEY");
Intent serviceIntent = new Intent(context , YOUR_SERVICE.class);
context.startService(serviceIntent );
}
感谢。