Есть некоторые проблемы с вашим кодом.
Во-первых, если вам нужно обновить индикатор выполнения операции из службы, эффективный способ - использовать LocalBroadcastManager
вместо обычной трансляции (известной как глобальная).широковещание).
Во-вторых, поскольку в службе вы используете broadcastIntent.setAction("com.example.services.MainActivity");
, а затем в упражнении вы должны использовать то же действие для получения широковещания.
IntentFilter filter = new IntentFilter("com.example.services.MainActivity");
вместо
IntentFilter filter = new IntentFilter(ACTION_ATTACH_DATA);
Наконец, поскольку вы используете AsyncTask в службе, чтобы избежать утечки контекста службы, рекомендуется объявлять asynctask как статический класс.
Соберите все вместе.
MyService.java
public class MyService extends Service {
int counter = 0;
static final int UPDATE_INTERVAL = 1000;
private Timer timer = new Timer();
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
doSomethingRepeatedly();
try {
new DoBackgroundTask(this).execute(
new URL("http://www.amazon.com/somefiles.pdf"),
new URL("http://www.wrox.com/somefiles.pdf"),
new URL("http://www.google.com/somefiles.pdf"),
new URL("http://www.learn2develop.net/somefiles.pdf"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.d("MyService", String.valueOf(++counter));
}
}, 0, UPDATE_INTERVAL);
}
// Declare asynctask as static class.
private static class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
// Using WeakReference to keep the context of the service to avoid leaking.
private WeakReference<Context> mContext;
DoBackgroundTask(Context context) {
mContext = new WeakReference<>(context);
}
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalBytesDownloaded = 0;
for (int i = 0; i < count; i++) {
totalBytesDownloaded += DownloadFile(urls[i]);
//Intent broadcastIntent = new Intent();
//broadcastIntent.setAction(Intent.ACTION_ATTACH_DATA);
//sendBroadcast(broadcastIntent);
publishProgress((int) (((i + 1) / (float) count) * 100));
}
return totalBytesDownloaded;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("Downloading files", String.valueOf(progress[0]) + "% downloaded");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.example.services.MainActivity");
//broadcastIntent.putExtra("progress",progress);
broadcastIntent.setFlags(progress[0]);
Context context = mContext.get();
if (context != null) {
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcastIntent);
int counter = ((MyService)context).counter;
Toast.makeText(context,
String.valueOf(progress[0]) + "% downloaded-" + counter,
Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(Long result) {
Context context = mContext.get();
if (context != null) {
Toast.makeText(context, "Downloaded " + result + " bytes",
Toast.LENGTH_LONG).show();
//stopSelf();
}
}
private int DownloadFile(URL url) {
try {
//---simulate taking some time to download a file---
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//---return an arbitrary number representing
// the size of the file downloaded---
return 100;
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyBroadRequestReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
// Register broadcast receiver.
IntentFilter filter = new IntentFilter("com.example.services.MainActivity");
receiver = new MyBroadRequestReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
@Override
protected void onStop() {
// Unregister broadcast receiver.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
public class MyBroadRequestReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
int progress = intent.getFlags();
pb.setProgress(progress);
}
}
}