问题
I'm trying to create a lockscreen. When I try to start the com.fira.locker.LockScreenActivity
from the broadcastReceiver, I just get an error. The error says:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setFlags(int)' on a null object reference
This is my code:
package com.fira.locker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by Johannett321 on 10/04/16.
*/
public class LockScreenReceiver extends BroadcastReceiver {
public String screenlockedNumber;
@Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.fira.locker", "com.fira.locker.LockScreenActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
回答1:
Why are you not starting simple intent like this..
startActivity(new Intent(this, LockScreenActivity.class));
finish();
or you can try this..
Intent i = new Intent(context,LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
回答2:
Use this code. Hope it help you.
Intent i= new Intent(context.getApplicationContext(), LockScreenActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
来源:https://stackoverflow.com/questions/38815216/trying-to-start-an-activity-from-broadcast-receiver