简体   繁体   中英

Not able to register Broadcast receiver Dynamically

I am registering my reciver in OnResume and unregistering in OnPause is Something is wrong with my code

package com.bd2;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
 import android.provider.Contacts.People;
import android.util.Log;

public class BroadcastReceiver2Activity extends Activity {
/** Called when the activity is first created. */
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
IntentFilter intentfilter;



  @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    intentfilter = new IntentFilter(); 
    intentfilter.addAction("android.intent.action.AIRPLANE_MODE");


}

 @Override
  protected void onResume() {
    // TODO Auto-generated method stub
   super.onResume();
   /*intfilter = new IntentFilter();
      intfilter.addAction("android.intent.action.AIRPLANE_MODE");*/
   registerReceiver(receiver, intentfilter);
   //       sendBroadcast();

  }

   @Override
    protected void onPause() {
    // TODO Auto-generated method stub
   super.onPause();
    unregisterReceiver(receiver);


    }

   private BroadcastReceiver receiver=new BroadcastReceiver(){


    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
          Notification notifyDetails = new Notification(R.drawable.icon,"Time Reset!",System.currentTimeMillis());
          PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);
          notifyDetails.setLatestEventInfo(context, "Time has been Reset", "Click on me to view Contacts", myIntent);
          notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
          mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
                Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");
    }

   }; 



   }

////////MANIFEST FILE

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.bd2"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".BroadcastReceiver2Activity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>



</application>

I am not getting my notification. If I'm doing this statically then it works

Edit #3: Define global variable:

private IntentFilter mIntentFilter;

From the onCreate handler:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mIntentFilter.addAction("android.intent.action.SERVICE_STATE");
    mIntentFilter.addAction("android.intent.action.AIRPLANE_MODE");
    registerReceiver(receiver, mIntentfilter);
}

From the onResume handler:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
   super.onResume();
    // Be careful here... mIntentFilter might be gc'd! add checking to this!
   registerReceiver(receiver, mIntentFilter);
   Log.d(TAG, "onResume() - Registered!");
}

From the onPause handler:

@Override
protected void onPause() {
   // TODO Auto-generated method stub
   unregisterReceiver(receiver);
   Log.d(TAG, "onPause() - Unregistered!");
   super.onPause();
}

From the broadcast receiver:

private BroadcastReceiver receiver=new BroadcastReceiver(){
@Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (intent != null && intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){
           Log.d(TAG, "receiver/onReceive() - GOT THE INTENT!!!!");
        }else{
           Log.d(TAG, "receiver/onReceive() - NOPE! NO INTENT!");
        }
        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
          Notification notifyDetails = new Notification(R.drawable.icon,"Time Reset!",System.currentTimeMillis());
          PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);
          notifyDetails.setLatestEventInfo(context, "Time has been Reset", "Click on me to view Contacts", myIntent);
          notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
          mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
                Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");
    }

   };

At this point, remove the intent receiver (that I mentioned earlier) from the manifest as we're doing this programmatically. Also, define the permission!

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Everything looks good to me other than the fact that you can't turn airplane mode on or off without pausing your Activity, which unregisters your receiver. By the time you get back to your Activity, resuming and re-registering, you've missed the broadcast.

I have no idea what your ultimate goal is here, but if you want your app to receive the airplane mode Intent, the best idea is to register in your manifest. (Technically you can do it dynamically, but that would require doing the registration/unregistration somewhere more permanent than onResume() / onPause() which I don't think is really what you want.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM