尝试从广播接收器启动一个活动

3

我正在尝试创建一个锁屏界面。当我尝试从broadcastReceiver启动com.fira.locker.LockScreenActivity时,会出现错误。错误信息如下:

 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setFlags(int)' on a null object reference

这是我的代码:
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);
        }
}
2个回答

5
请使用这段代码。希望能帮到你。
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);

谢谢,@karimkhan Intent.FLAG_ACTIVITY_CLEAR_TOP 对我有用。 - Rishi

1
为什么你不像这样开始简单意图呢?
startActivity(new Intent(this, LockScreenActivity.class));
finish();

或者你可以尝试这个...
Intent i = new Intent(context,LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

谢谢,最后一个有效。我觉得第一个在广播接收器中不起作用。 - Johan Svartdal
如果我们提供活动的上下文,它就会起作用。顺便问一下,你的问题解决了吗? - Pranav Fulkari
是的,我的问题已经解决了。问题甚至不在我分享的代码中,而是在LockScreenActivity类中... - Johan Svartdal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接