一、环境
- 安卓系统:4.2
- 操作系统:Win 8.1
- 工具:Android Studio
二、利用广播开启后台服务
- 定义一个广播接收器类(MyBroadcastReceive)继承自 BroadcastReceive,重写里面的 onReceive 方法,即可在接收到广播后做出相应操作。
public class MyBroadcastReceiver extends BroadcastReceiver {
private final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//后边的XXX.class就是要启动的服务
Intent service = new Intent(context,NofyService.class);
context.startService(service);
Log.v(TAG, "onReceive");
}
}
- 定义一个服务(MyService)继承自 Service ,并重写 onCreate、onStartCommand、onDestroy 方法即可。onCreate 方法在服务被创建时调用,onStartCommand 在服务开始后调用,如果 Activity 多次调用 Service,则只会在第一次调用 onCreate,其他都是调用 onStartCommand。
public class NofyService extends Service {
private final String TAG = "NofyService";
private Intent in;
private int flags;
private int startId;
@Nullable
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public void onCreate() {
Toast.makeText(getApplication(), "service", Toast.LENGTH_SHORT).show();
Log.v(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.in = intent;
this.flags = flags;
this.startId = startId;
new Thread(checkTime).start();
Toast.makeText(getApplication(), "service",
Toast.LENGTH_SHORT).show();
Log.v(TAG, "onStart");
return START_STICKY;
}
//Service 的功能,创建通知栏通知
Runnable checkTime = new Runnable() {
@Override
public void run() {
Calendar ca = Calendar.getInstance();
//利用 Notification 类设置通知的属性
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("事件提醒")
.setContentText("有事件")
//不设置小图标通知栏显示通知(不确定)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
notification.flags = Notification.FLAG_INSISTENT;
//利用 NotificationManager 类发出通知栏通知
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(1, notification);
}
};
@Override
public void onDestroy() {
this.onStartCommand(in, flags, startId);
}
}
- 在 AndroidManifest.xml 注册 MyBroadcastReceive。
<!-- 广播接收器 -->
<receiver android:name=".broadcastReceiver.MyBroadcastReceiver">
<intent-filter >
<action android:name="com.cj_finger.broadcast" />
</intent-filter>
</receiver>
- 在 AndroidManifest.xml 注册 MyService。
<!-- 服务 -->
<service android:name=".service.NofyService" android:process=":NofyService" >
<intent-filter>
<action android:name="com.cj_finger.service.NofyService" />
</intent-filter>
</service>
- *添加开机启动权限(开机启动,有的手机厂家会屏蔽开机广播)。
<!-- 开机自启权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
- *还要设置 MyBroadcastReceive 的注册信息。
<!-- 广播接收器 -->
<receiver android:name=".broadcastReceiver.BootBroadcastReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
网友评论