我正在尝试制作应用程序,我正在制作服务器请求并获得响应,而我正在收到回复,即使应用程序被杀,我也会显示通知。所以这就是为什么我把所有这些都用在服务中并且在得到响应之后我从服务器响应中获得广播信息到广播接收器活动中显示在应用程序中显示的recyclerview.info中的信息(没有点击通知但是连续的网络请求和响应)因为我做直接广播,但我点击通知没有显示在recyclerview。怎么解决这个..
NotificationActivity:
public class NotificationActivity extends AppCompatActivity {
GetPostAsyncTask backgroundTask;
ArrayList<NotificationDataClass> list;
NotificationListShowAdapter notificationListShowAdapter;
RecyclerView recyclerView;
Context contextNotificationActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
Intent intent=new Intent(NotificationActivity.this,ServiceClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
contextNotificationActivity=NotificationActivity.this;
recyclerView=(RecyclerView)findViewById(R.id.recyclerViewId);
/*notificationListShowAdapter=new NotificationListShowAdapter(contextNotificationActivity,list);
LinearLayoutManager layoutManager=new LinearLayoutManager(contextNotificationActivity);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationListShowAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(contextNotificationActivity,
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
notificationListShowAdapter.notifyDataSetChanged();*/
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(broadcastReceiver,new IntentFilter("Notification"));
}
private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Receiver",Toast.LENGTH_LONG).show();
String result=intent.getStringExtra("Result");
Log.v("Brd",intent.getStringExtra("Result"));
JSONObject jsonObject= null;
list=new ArrayList<>();
try {
jsonObject = new JSONObject(result);
// JSONObject codeObj=jsonObject.optJSONObject("code");
JSONArray jsonArray=jsonObject.getJSONArray("payload");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=new JSONObject(jsonArray.optString(i));
NotificationDataClass notificationDataClass=new NotificationDataClass();
notificationDataClass.setName(jsonObject1.getString("Name"));
notificationDataClass.setRemarks(jsonObject1.getString("Remarks"));
Log.v("hsdgfjgsdh", String.valueOf(jsonObject1.getInt("Type")));
if(jsonObject1.getInt("Type")==1){
notificationDataClass.setInout("In");
}else {
notificationDataClass.setInout("Out");
}
notificationDataClass.setTime(jsonObject1.getString("DateTime"));
list.add(i,notificationDataClass);
}
notificationListShowAdapter=new NotificationListShowAdapter(context,list);
LinearLayoutManager layoutManager=new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationListShowAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context,
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
notificationListShowAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(broadcastReceiver);
}
}
服务类:
public class ServiceClass extends Service {
GetPostAsyncTask_ServiceClass backgroundTask;
Context context;
Handler handler;
Runnable runnable;
LocalBroadcastManager localBroadcastManager;
int iny=1;
@Override
public void onCreate() {
super.onCreate();
localBroadcastManager=LocalBroadcastManager.getInstance(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
context=getApplicationContext();
handler=new Handler();
runnable=new Runnable() {
@Override
public void run() {
String queryForNotification=null;
try {
queryForNotification = URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode("03/13/2017", "UTF-8");
Log.v("INRTR","out"+iny++);
backgroundTask=new GetPostAsyncTask_ServiceClass(context);
backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"GET","GetHrOnDutyActivityByDate?"+queryForNotification,"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(1000);
handler.postDelayed(runnable,10000);
}
};
handler.postDelayed(runnable,10000);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
//Asynctask
private class GetPostAsyncTask_ServiceClass extends AsyncTask<String, Void, String> {
// public AsyncResult asyncResult;
ProgressDialog progressDialog;
private final String baseUrl = "http://192.168.0.6:880/MobileAPI/";
Context context;
GetPostAsyncTask_ServiceClass(Context context) {
this.context = context;
// this.asyncResult = asyncResult;
}
@Override
protected void onPreExecute() {
//Toast.makeText(context,"Loading..",Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(context);
// progressDialog.show();
}
@Override
protected String doInBackground(String... args) {
try {
// setting the URL
URL url = new URL(baseUrl + args[1]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.addRequestProperty("Apiuser", "SDLPayrollAPI");
httpURLConnection.addRequestProperty("Apikey", "DFGHJ*UH45445^TY");
// setting the method type
httpURLConnection.setRequestMethod(args[0]);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// setting the identification key name with query params
bufferedWriter.write(args[2]);
bufferedWriter.flush();
bufferedWriter.close();
httpURLConnection.connect();
String line = "";
String res = "";
// prepare the output buffer
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
res += line;
}
inputStream.close();
httpURLConnection.disconnect();
return res.toString();
} catch (IOException e) {
Log.v("PesDSS","doBCa"+e.toString());
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("PesDSS","out"+result);
Intent intent1;
// progressDialog.dismiss();
if (result != null) {
// asyncResult.asyncResult(result);
Log.v("PesDSS","in"+result);
//notification
NotificationCompat.Builder notification=new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.systech_logo)
.setContentTitle("Notification")
.setContentText("Delivered")
.setAutoCancel(true)
;
intent1 = new Intent(context, NotificationActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setAction("Notification");
intent1.putExtra("Result",result);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
TaskStackBuilder taskStackBuilder=TaskStackBuilder.create(context);
taskStackBuilder.addParentStack(NotificationActivity.class);
taskStackBuilder.addNextIntent(intent1);
PendingIntent pendingIntent=taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,intent1,PendingIntent.FLAG_CANCEL_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notification.build());
}
}
}
}
通知数据类:
public class NotificationDataClass {
String name;
String remarks;
String inout;
String time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getInout() {
return inout;
}
public void setInout(String inout) {
this.inout = inout;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
我试图遵循Stack Overflow的解决方案,但我无法解决它。任何帮助将不胜感激!
答案 0 :(得分:1)
仅当您当前的活动位于前景或可见时才会调用FYI onReceive()
。对于点击通知执行任务,当您的活动/应用程序处于后台时,您也应该在onCreate()
中执行与onReceive()
中相同的操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
Intent notificationIntent = getIntent.getStringExtra("Result");
if(notificationIntent != null){
//do whatever you have done in onReceive().
}
}