【发布时间】:2015-05-19 08:39:19
【问题描述】:
我想在电源连接到我的设备并显示通知时启动一项服务,但我的应用程序什么也不做,或者我没有发生什么,所以请帮助我,我是 android 世界的新手,也许我错过了什么,mi代码如下:
我的清单:
<receiver android:name="com.tlm.grhs_client.WiFiMonitor">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
</intent-filter>
</receiver>
我的广播接收器:
public class WiFiMonitor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI) {
if (info.isConnected()) {
//iniciar servicio
Intent serviceIntent = new Intent(context, ClientService.class);
context.startService(serviceIntent);
}
else {
//parar servicio
Intent serviceIntent = new Intent(context, ClientService.class);
context.stopService(serviceIntent);
}
}
}
}
我的服务等级是这样的:
public class ClientService extends Service {
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Toast.makeText(this, "Servicio fue creado", Toast.LENGTH_LONG).show();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("NewApi")
@Override
public void onStart(Intent intent, int startId) {
// Perform your long running operations here.
Toast.makeText(this, "Servicio iniciado", Toast.LENGTH_LONG).show();
Notification.Builder notiBuilder = new Notification.Builder(this);
notiBuilder.setContentTitle("Prueba");
notiBuilder.setContentText("Esto es una prueba");
Notification notificacion = notiBuilder.build();
NotificationManager manager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
manager.notify(1, notificacion);
}
@Override
public void onDestroy() {
Toast.makeText(this, "Servicio destruido", Toast.LENGTH_LONG).show();
}
}
我打开wifi并建立连接,但没有显示通知。
【问题讨论】:
标签: service broadcast intentfilter