Start new Activity From BroadcastReceiver or Service Class
Hello have to start a new Activity from the BroascastReceiver or the Service, but I have found error that cant start activity without activity context.
I use the following code
Intent i=new Intent(this,MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
开发者_开发百科
And also include the activity in Mainifest file,
Please resolve it,
And another second problem is, I start a service inside the BroadcastReceiver but this Service finish when BroadcastReceiver lifecycle completes. I want to keep alive the Serive
Please help me on this
While I can't provide solution to your 1st question, I'll answer the second one.
@Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context, SampleService.class);
context.getApplicationContext().startService(intent);
}
Also, Android SDK developers don't recommend to start activities from broadcast receivers or services.
use context
instead of this
like this:
Intent i=new Intent(context,MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
register your service in the manifest
file and use startservice
.
This code worked fine for me
public void onReceive(Context context, Intent intent) {
Log.v(Tag, "Start Listening Phone Call");
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_IDLE:
Log.v(Tag, "No call");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.v(Tag, "A new call arrived and is ringing or waiting");
Intent i = new Intent(context,MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
break;
}
精彩评论