Johan Svartdal Johan Svartdal - 4 months ago 38
Android Question

Trying to start an activity from broadcast receiver

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);
}
}

Answer

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);