我有一个活动在另一个访问sharedpreferences的类中运行一个方法。我想创建一个可以通过单击按钮运行相同方法的小部件。只要应用程序在后台打开,它就可以正常工作,但如果它关闭,当我按下小部件上的按钮时,应用程序会崩溃。
我很确定这是因为我需要访问共享偏好的上下文,并且我尝试单独从活动和窗口小部件传递上下文但它不起作用。
基本上,当方法在另一个类中时,如何从窗口小部件访问共享偏好?
活动代码:
public class MainActivity extends AppCompatActivity {
protected static Context context;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.context = getApplicationContext();
}
public void panicFromView(View view){
prefs = PreferenceManager.getDefaultSharedPreferences(context);
Methods.panic(prefs);
}
}
小工具代码:
public class PanicWidget extends AppWidgetProvider {
public static final String CLICK_PANIC = "PANIC";
SharedPreferences prefs;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.panic_widget);
Intent intent = new Intent(context, PanicWidget.class);
intent.setAction(CLICK_PANIC);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.panicButton, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
public void onReceive(Context context, Intent intent){
super.onReceive(context, intent);
if (CLICK_PANIC.equals(intent.getAction())){
panicFromWidget(prefs);
}
}
public void panicFromWidget(SharedPreferences prefsIn){
Methods.panic(prefsIn);
}
}
方法:
public class Methods {
public static Context getAppContext() {
return MainActivity.context;
}
public static void panic(SharedPreferences prefsIn){
//loops through contacts
for (int i = 1; i <= 5; i++) {
String contactKey = "contact-sms" + i;
String contactNo = getContact(contactKey, prefsIn);
//sends sms only if contact number exists
if (!contactNo.equals("")) {
sendSMS(contactNo);
}
}
}
//returns contact number from contact name
public static String getContact(String key, SharedPreferences prefsIn){
return prefsIn.getString(key, null);
}
//sends SMS to contact number
public static void sendSMS(String phoneNo){
try{
String msg = "test";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getAppContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {}
}
}
答案 0 :(得分:0)
没关系,它确实有效。不知何故,我的共享偏好在我不知情的情况下被清除,因此它抛出了一个nullpointerexception。