我正在使用具有多个意图过滤器的广播接收器。我的要求是访问通知点击并在后台(如果应用最小化)或前景中单击该作业。前两个工作正在完成,但第三个工作没有执行。哪里错了? 这是我的代码
public class MainActivity extends Activity{
int choice; EditText et;
@override
onCreate(Bundle SavedInstanceState){
setContentView(R.layout.main);
et= (EditText)findViewById(R.id.choice);
choice=Integer.parseInt(et.getText().toString());
//some_stuff
if (choice==1)
registerReceiver(br, new IntentFilter("ACT_ONE");
else if (choice==2){
registerReceiver(br, new IntentFilter("ACT_TWO");
registerReceiver(br, new IntentFilter("ACT_THREE");
}
else if (choice==3) {
NotificationCompat.Builder nb=new NotificationCompat.Builder(this);
nb.setContentTitle("Do Job_Four");
nb.setContentText("Click here to do job four");
nb.setAutoCancel(true);
nb.setSmallIcon(R.drawable.icon);
nb.setDefaults(Notification.DEFAULT_ALL);
Intent in=new Intent(this,MainActivity.class);
IntentFilter lf=new IntentFilter("ACT_FOUR");
PendingIntent pi=PendingIntent.getBroadcast(this,(int)System.currentTimeMillis(),in,0);
nb.setContentIntent(pi);
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
registerReceiver(br,lf);
nm.notify((int)System.currentTimeMillis(),nb.build());
}
}
private void m_one(){
//job_one_code
}
private void m_two(){
//job_two_code
}
private void m_three(){
//job_three_code
}
BroadcastReceiver br=new BroadcastReceiver(){
@override
onReceive(Context c, Intent i){
if(i.getAction().equals("ACT_ONE")
m_one();
else if(i.getAction().equals("ACT_TWO")
m_two();
else if(i.getAction().equals("ACT_THREE")
m_two();
else if(i.getAction().equals("ACT_FOUR")
m_three();
}
};
@override
public void onDestroy(){
unregisterReceiver(br);
super.onDestroy();
}
}
这是清单
<receiver android:name=".MainActivity">
<intent-filter android:priority="999">
<action android:name="ACT_ONE"/>
</intent-filter>
</receiver>
答案 0 :(得分:0)
my pseudo code:-- Please register onPause() and unregister
on onResume() method it will work.
public class AndroidBroadcast extends Activity {
private BroadcastReceiver the_receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context c, Intent i) {
}
};
// Set When broadcast event will fire.
private IntentFilter filter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent();
intent.setAction("ax.chayan.mybroadcast");
sendBroadcast(intent);
}
@Override
protected void onResume() {
// Register reciever if activity is in front
this.registerReceiver(the_receiver, filter);
super.onResume();
}
@Override
protected void onPause() {
// Unregister reciever if activity is not in front
this.unregisterReceiver(the_receiver);
super.onPause();
}
}