简体   繁体   English

我的Android服务导致应用崩溃

[英]My android service causes the app to crash

I'm trying to call a method of another class but this causes my app to crash. 我试图调用另一个类的方法,但这会导致我的应用程序崩溃。

This is what I'm doing to run it on boot 这就是我在引导时运行它的目的

public class BootReceiver extends BroadcastReceiver{

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

I've commented out all the lines from run_service() to find out what the cause is, and it's this line 我已经注释掉run_service()的所有行,以找出原因,这就是这一行

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

It works fine if I call it from within that class (when the application is the foreground), so why can't I call it from inside onReceieve? 如果我从该类中调用它(当应用程序是前台)时,它可以正常工作,那么为什么不能从onReceieve内部调用它呢?

Updated to add notification code: 更新以添加通知代码:

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

try this way call this way 尝试这种方式叫这种方式

test.run_service(context);

your run method 您的运行方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM