我登記我的reciver中的onResume和註銷的onPause的東西是錯我的代碼無法註冊廣播接收器動態
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");
}
};
}
////////清單文件
<?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>
我沒有收到我的通知。如果我這樣做是靜態的,然後它工作
這是一個非常好的問題,因爲別人稍後會遇到這種情況。 :)動態註冊廣播接收機..:D – t0mm13b
@ t0mm13b動態註冊廣播接收機很容易,維基做的是正確的。這個問題是我昨天在回答中指出的:您需要暫停活動(取消註冊接收器)以打開/關閉飛行模式。因此你錯過了播放。這是*不應該被動態註冊的接收器的一個例子。 –