Trying to start an activity from broadcast receiver

浪尽此生 提交于 2021-02-08 03:43:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!