gpt4 book ai didi

java - 我的 Android 服务导致应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 15:47:35 25 4
gpt4 key购买 nike

我正在尝试调用另一个类的方法,但这会导致我的应用程序崩溃。

这就是我在启动时运行它所做的事情

public class BootReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
MyApp test = new MyApp();
test.run_service();
}
}

我已经注释掉了 run_service() 中的所有行以找出原因,就是这一行

SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);

如果我从该类中调用它(当应用程序是前台时),它工作得很好,那么为什么我不能从 onReceieve 内部调用它呢?

更新以添加通知代码:

CharSequence title = "MyApp";
CharSequence message = "Hello World";

NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.icon, "Hi!", System.currentTimeMillis());

Intent notificationIntent = new Intent(context, MyApp.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
n.setLatestEventInfo(MyApp.this, title, message, pendingIntent);
nm.notify(NOTIFICATION_ID, n);

最佳答案

试试这个方法这样调用

test.run_service(context);

你的运行方法

void run_service(Context context){
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
}

关于java - 我的 Android 服务导致应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6845469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com