1,建立StatusBarService.java类(名字可以自取)
代码如下:
package com.dd.dd;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
public class StatusBarService extends IntentService {
private static final String TAG = "StatusBarService";
private static final int KUKA = 0;
public StatusBarService() {
super("StatusBarService");
}
@Override
protected void onHandleIntent(Intent arg0) {
Log.i(TAG, "开始下载");
showNotification();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
showNotification2();
Log.i(TAG, "文件下载完毕");
}
@SuppressWarnings("deprecation")
private void showNotification() {
Notification notification = new Notification(R.drawable.icon, "开始下载",
System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, "下载", "正在下载中。。。", contentIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(KUKA, notification);
}
private void showNotification2() {
Notification notification = new Notification(R.drawable.icon, "下载完毕!!!",
System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, "下载完毕", "你可以点击查看下载好的内容!", contentIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(KUKA, notification);
}
}
2,第二步在AndroidManifest.xml文件中把服务加进去
<service android:name=".StatusBarService" />
3,在布局文件中添加按钮,用来启动服务,我默认在activity_main.xml文件中
<Button
android:id="@+id/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="80dp"
android:background="@drawable/shape"
android:text="启动下载" />
4,在MainActivity.java中加入:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
down = (Button) findViewById(R.id.down);
down.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
StatusBarService.class);
Toast.makeText(MainActivity.this, "程序已经在下载了!",
Toast.LENGTH_LONG).show();
startService(intent);
}
});
}
版权声明:本文为博主原创文章,未经博主允许不得转载。