【问题标题】:starting BroadcastReceiver from Service when app destroy?应用程序销毁时从服务启动广播接收器?
【发布时间】:2016-09-11 01:04:45
【问题描述】:

我的应用程序中的广播接收器和服务有问题 ………… 我有一个 * 活动( MainActivity ) * 服务(通知服务) * 接收方(NotifyBroadcast)

服务从活动开始,然后接收者从服务开始

当我的应用程序打开时一切都很好,但是当我清除它(销毁)时,接收器停止工作(只是一条祝酒消息)

这是我的代码: 主要活动..

 if( !NotifyService.ServiceIsRun){
        NotifyService.ServiceIsRun=true;
        startService(new Intent(this, NotifyService.class));
    }

通知服务 ..

public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {       
    Timer t = new Timer();
    if(ServiceIsRun){
        t.scheduleAtFixedRate(new TimerTask() {

                                  @Override
                                  public void run() {
                                      Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
                                      i++;
                                      Intent intent = new Intent( "com.latestBabiaNews" );
                                      sendBroadcast(intent);
                                  }

                              },
                //Set how long before to start calling the TimerTask (in milliseconds)
                0,
                //Set the amount of time between each execution (in milliseconds)
                20000);
    }

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

通知广播..

public class NotifyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    final  Bundle bundle = intent.getExtras();
    if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){ 
       Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();

    }

}
}

在我的清单中..

<service android:name=".NotifyService"></service>
    <receiver android:name=".NotifyBroadcast">
        <intent-filter>
            <action android:name="com.latestBabiaNews"></action>
        </intent-filter>
    </receiver>

....... 最后,当应用程序打开时,我可以显示 Toast 消息,但是当我清除它时,我无法显示任何内容!

【问题讨论】:

    标签: android service broadcastreceiver ondestroy


    【解决方案1】:

    为了防止服务终止,请将其用作前台服务。要将其作为前台执行,请使用此(在 Service 类中):

    @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
    
            fg();
        }
    private void fg() {
            Intent intent = launchIntent(this);
            PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
            mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
                .setContentText(getResources().getString(R.string.app_alias))
                .setContentIntent(pIntent);
    
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                mBuilder.setSmallIcon(someicon);
            } else {
    
                mBuilder.setSmallIcon(someicon);
                mBuilder.setColor(somecolo);
            }
            noti = mBuilder.build();
            noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
            startForeground(_.ID, noti);
    
        }
    

    停下来,这个:

    @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            stopForeground(true);
    
        }
    

    编辑

    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.support.v4.content.WakefulBroadcastReceiver;
    
    public class MyBroadCast extends WakefulBroadcastReceiver {
        public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
        @Override
        public void onReceive(Context ctx, Intent intent) {
             Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
        }
    
    }
    

    开始使用这个:

    public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
            AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
            Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
            if (autoStart)
                intent.putExtra(_.AUTOLOADSERVICE,true);
    
            PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
                am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
            } else {
                if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
                    am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
                } else {
                        am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
                }
            }
            //or use repeating:
            //am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); 
        }
    

    【讨论】:

    • 我只想显示 toast 消息,为什么我需要通知?
    • 如果你想确保服务不会被杀死,你必须使用前台
    • @OuailBellal 最好用AlarmManager
    • @OuailBellal ,使用广播类和第二个函数来启动alarmmanager。根本不需要这项服务。
    • @Vyacheslav 你能回答这个问题吗stackoverflow.com/questions/39343099/…拜托,我震惊了将近一个星期。
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多