我在java / android中的代码有一个小问题。
目前在MainActivity中使用此代码:
private class GetNotifications extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(ApiJsonNotificationsURL);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray notifications = jsonObj.getJSONArray("notifications");
for (int i = 0; i < notifications.length(); i++) {
JSONObject n = notifications.getJSONObject(i);
int id = (i);
String title = n.getString("title");
String message = n.getString("message");
String image = n.getString("image");
//notification
MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
if(image.equals("null")){
mNotificationManager.showSmallNotification(id, title, message, intent);
}else{
mNotificationManager.showBigNotification(id, title, message, image, intent);
}
//notification
}
} catch (final JSONException e) {
/*runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});*/
}
} else {
/*runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});*/
}
return null;
}
}
我用这种方式打电话给他:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetNotifications().execute();
}
如何在AlarmReceiver中使用新的GetNotifications()。execute():
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
Toast.makeText(context, "here i want use GetNotifications", Toast.LENGTH_SHORT).show();
}
}
我是JAVA的初学者,我不知道该怎么做。我一直试图这样做几天。它将错误返回到“上下文”。有人能帮我吗?
您可以在AsyncTask
中使用相同的AlarmReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
Toast.makeText(context, "here i want use GetNotifications", Toast.LENGTH_SHORT).show();
new GetNotifications(context).execute();
}
private class GetNotifications extends AsyncTask<Void, Void, Void> {
private Context context;
public GetNotifications(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
return null;
}
}
}
并使用Context
方法的onReceive
。