当我从后台删除我的程序时,我的Receiver类失败了

时间:2016-04-06 21:13:03

标签: android broadcastreceiver android-manifest intentfilter

我有一个Receiver类,用于检查手机是否已插入充电器或从充电器上拔下。我想在拔下手机时播放声音(使用通知)。

以下是我的课,它的工作正确。但是当我从“启动最近的程序”窗口关闭我的程序时,只有这部分力量关闭(我仍然可以看到Toast“CONNECTED”),为什么?

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {
static int num = 0;
public static SharedPreferences sharedPreferences;
Notification notification = new Notification();
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
        Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
    }
    else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {

        Toast.makeText(context, "" + num, Toast.LENGTH_LONG).show();

        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        String strRingtonePreference = sharedPreferences.getString("song", null);
        Toast.makeText(context, "" +strRingtonePreference, Toast.LENGTH_LONG).show();
        notification.sound = Uri.parse(strRingtonePreference);
        nm.notify(0, notification);
        num++;
    }
}

这是我的mainActivity.java

public class MainActivity extends Activity {
public String path = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button) findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            path = load();
            Toast.makeText(getBaseContext(),"" + (path == null), Toast.LENGTH_SHORT).show();
            startActivityForResult(intent, 1);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
        if (uri != null) {
            String ringTonePath = uri.toString();
            TextView t = (TextView)findViewById(R.id.textView);
            t.setText(ringTonePath);
            save(ringTonePath);
        }
    }
}

private void save(String ringTonePath) {

    MyReceiver.sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = MyReceiver.sharedPreferences.edit();
    editor.putString("song", ringTonePath);
    editor.putInt("times" , 3);
    editor.apply();
}
private String load() {
    MyReceiver.sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    return MyReceiver.sharedPreferences.getString("song", null);
}

}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.n.receiver" >
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

正如我所怀疑的那样,您在清单中<intent-filter>附加了BroadcastReceiver。这意味着即使您的应用未运行,Android也会实例化您的BroadcastReceiver并致电onReceive()。在这种情况下,sharedpreferences中的变量MyReceiver为空,因为它尚未初始化,onReceive()会抛出NullPointerException

如果您只想在应用运行时获取这些广播Intent,请从清单中移除<intent-filter>,然后使用BroadcastReceiver在代码中注册registerReceiver()