【问题标题】:How to make my service run?如何让我的服务运行?
【发布时间】: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


    【解决方案1】:

    按照http://developer.android.com/guide/topics/ui/notifiers/notifications.html 的文档,这种方式的 Android 通知需要一个小图标、标题和一些文本

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

    【讨论】:

    • 是的,看起来它应该可以工作,但它不起作用,我已经在我的代码中编写了通知的大小图标,但它仍然不起作用。
    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 2017-04-06
    • 2020-04-21
    • 2020-08-23
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多