如何让我的服务运行?

时间:2015-03-17 02:21:06

标签: service broadcast intentfilter

我想在电源连接到我的设备并显示通知但我的应用程序什么都不做或者我不知道发生什么事情时启动服务,所以请帮助我,我是android世界的新手,也许我想念一下,mi代码如下:

我的清单:



<receiver android:name="com.tlm.grhs_client.WiFiMonitor">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    </intent-filter>
</receiver>
&#13;
&#13;
&#13;

我的广播接收者:

&#13;
&#13;
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);
           }
       }
    }
}
&#13;
&#13;
&#13;

我的服务类就是:

&#13;
&#13;
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();
	}

}
&#13;
&#13;
&#13;

我打开wifi并建立连接,但通知没有显示。

1 个答案:

答案 0 :(得分:0)

根据http://developer.android.com/guide/topics/ui/notifiers/notifications.html

的文档,以这种方式的Android通知需要一个小图标,以及标题和一些文字

添加一个图标,但代码(快速浏览)看起来应该可以正常工作。