我有一项服务,我用它来使用Http将一些文件上传到服务器。我想在上传文件时显示进度指示器。最初,我使用startForeground()方法在传输过程中显示简单的通知。我现在想要使用从Google Play商店下载应用程序时显示的进度指示器。我按照http://developer.android.com/guide/topics/ui/notifiers/notifications.html#CustomExpandedView
上显示的示例进行了剪辑但是在我的服务中实现它会导致RuntimeException。我的Service类中的代码如下:
public int onStartCommand(Intent intent, int flags, int startId) {
Thread myThr = new Thread(new MyThreadClass());
myThr.start();
return START_STICKY;
}
public class SendSelectedNew extends Thread{
public void run(){
try{
if(fileSize()>0){
int fileSize = getSize();
for(int i = 0; i<fileSize;i++){
setNote(sizeOfTheList, i);
startForeground(1339, note);
mNotifyManager.notify(1339, note);
/*Code to upload files to my Server
*/
}
MyService mySer = MyService.this;
mySer.stopForeground(true);
mySer.stopSelf();
}
}catch(Exception e){
if(connection!=null){
connection.disconnect();
}
e.printStackTrace();
}
}
}
public void setNote(int fileSize, int progress){
note = new Notification.Builder(this).setContentText("Sending files").setSmallIcon(R.drawable.sendreceive).setContentTitle("MYApp").setProgress(fileSize, progress, false).build();
note.flags|= Notification.FLAG_NO_CLEAR;
}
我做错了什么?我不允许从服务中显示进度指示器吗?我没有在Logcat中为我的应用程序获取任何日志,但这是我在调试窗格中获得的
Thread [<1> main] (Suspended (exception RuntimeException))
ActivityThread.handleServiceArgs(ActivityThread$ServiceArgsData) line: 2782
ActivityThread.access$2000(ActivityThread, ActivityThread$ServiceArgsData) line: 152
ActivityThread$H.handleMessage(Message) line: 1385
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 137
ActivityThread.main(String[]) line: 5328
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 1102
ZygoteInit.main(String[]) line: 869
NativeStart.main(String[]) line: not available [native method]
答案 0 :(得分:0)
不要从线程调用setNote方法,而是在服务中实现一个侦听器:
public interface ProgressListener{
public abstract void onProgressChange(int progress);
}
public class MyService implements ProgressListener{
@Override
public void onProgressChange(int progress){
//update your UI, launch notification or whatever you want
}
}
然后在你的线程init中定义你的监听器:
ProgressListener myListener = mySer;
并在循环中调用onProgressChange:
myListener.onProgressChange(i);