我有一个活动,我用导航抽屉选项加载不同的片段。
这些片段具有不同的asynctasks(例如,一个用于下载图像,一个用于导入数据库等)。每次启动asynctask时,我都会使用NotificationManager来显示进度。
我正在寻找的是,如果有人点击任何通知,它将取消相应的AsyncTask。我读到了PendingIntent方法,但我不确定是否需要打开这样做的意图。
另外,我很困惑如何从我的MainActivity中获取AsyncTasks的引用,因为它们是在片段内启动的(并且这些片段会不时被破坏)。
如果你愿意,我可以在这里放一些代码,但代码是非常基本的AsyncTask和基于片段的导航抽屉,带有单个Activity。
谢谢,
public class MyFragment1 extends Fragment {
private DownloadFile asynctaskhandler;
public method(){
asynctaskhandler = new DownloadFile();
asynctaskhandler.execute();
}
private class DownloadFile extends AsyncTask<Void, String, Void> {
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
int mId;
protected Void doInBackground(Void... args) {
while(){
//DON SOMETHING, GET PROGRESS progress
mBuilder.setProgress(mId, progress, true);
mNotifyManager.notify(mId, mBuilder.build());
}
}
}
}
答案 0 :(得分:1)
对于这个问题中的许多问题......我将尝试回答有关通知的问题。
通知:
Intent intent2 = new Intent();
intent2.setAction("com.app.example.MyServiceClass.STOP");
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent2, 0);
noti = new NotificationCompat.Builder(this)
.setContentTitle("Recorder")
.setContentText("running")
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.drawable.ic_launcher, "Stop", pIntent)
.build();
startForeground(12345, noti);
服务(pendingIntent的接收者):
// registering BroadcastReceiver
IntentFilter filter2 = new IntentFilter();
filter2.addAction("com.app.example.MyServiceClass.STOP"); //further more
registerReceiver(receiver, filter2);
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("com.app.example.MyServiceClass.STOP")){
isCancelled = true; // this is a class variable
sendMessage("hide");
}
}
};
doInBackground:
protected Boolean doInBackground(String... StringUrls) {
// some loop
if (myServiceClass.this.isCancelled) {
myServiceClass.this.stopSelf();
}
// some loop
}