app破坏时从服务启动BroadcastReceiver?

时间:2016-09-10 14:10:18

标签: android service broadcastreceiver ondestroy

我对BroadcastReceiver&我的申请服务 ....... 我有一个 *活动(MainActivity) *服务(NotifyService) *接收者(NotifyBroadcast)

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

开始

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

这是我的代码: MainActivity ..

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

NotifyService ..

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;
}
}

NotifyBroadcast ..

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消息,但是当我清除它时我无法显示任何内容!

1 个答案:

答案 0 :(得分:0)

要防止服务终止,请将其用作前台服务。要将其作为前台使用,请使用此(在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); 
    }