【问题标题】:Intent Service doesn't run from Broadcast Receiver意图服务不从广播接收器运行
【发布时间】:2016-06-02 06:51:58
【问题描述】:

我使用AlarmManager:http://javatechig.com/android/repeat-alarm-example-in-android 遵循了Android 中的重复警报示例 本教程。 我想启动一个警报,该警报将每 10 秒触发一次意图服务。但是,如果有人可以帮助我,那就行不通了。

MainActivity代码:

package subhi.com.broadcast2;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        /* Retrieve a PendingIntent that will perform a broadcast */
        Intent alarmIntent = new Intent(MainActivity.this, MyService.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);

        findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });

        findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });

        findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAt10();
            }
        });
    }


    public void start() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 10000;

        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancel() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
    }

    public void startAt10() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 1000 * 60 * 20;

        /* Set the alarm to start at 10:30 AM */
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 30);

        /* Repeating on every 20 minutes interval */
        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                1000 * 60 * 20, pendingIntent);
    }
}

AlarmReciver 代码,它将启动 IntentService

package subhi.com.broadcast2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by subhi on 2/20/2016.
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // For our recurring task, we'll just display a message
       //Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
        Intent intent2=new Intent(context,MyService.class);

        context.startService(intent);
    }
}

MyService 代码:

package subhi.com.broadcast2;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by subhi on 2/20/2016.
 */
public class MyService extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyService() {
        super("My_Worker_Thread");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"Service Started....",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Stopped....",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Toast.makeText(getApplicationContext(),"Good",Toast.LENGTH_LONG).show();

        synchronized (this){


            int count=0;
            while (count<10) {
                try {
                    wait(3000);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }


    }
}

最后是清单代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="subhi.com.broadcast2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>


        <service android:name=".MyService">
        </service>
    </application>

</manifest>

【问题讨论】:

  • 当 AlarmSERVICE 将向广播接收器传递意图并且您可以在那里执行所有需要的逻辑时,您究竟为什么要使用 IntentService? ...无论如何,我看到的第一个直接问题是在您传递的 BroadcastReceiver 中:context.startService(intent);(方法参数 - 传递的意图)而不是 context.startService(intent2);(intent2 - 你打算做其他事情)
  • 同时查看您未在清单中添加权限的示例:&lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt;,除非您这样做,否则您的意图过滤器将不起作用。
  • 使用 BroadcastReceiver 或 IntentService,但不能同时使用。对于使用带有 PendingIntent 的 IntentService,基本上使用 getService() 而不是 getBroadcast(),这里有一些示例代码:stackoverflow.com/questions/30141631/…

标签: android android-intent broadcastreceiver intentservice


【解决方案1】:

广播接收器有一个 BOOT_COMPLETED 意图过滤器。因此接收器只会在启动完成时接收广播。而是在待处理的意图中使用您的 MyService 意图服务,如下所示

PendingIntent intent = PendingIntent.getService(context, 0, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);

【讨论】:

    猜你喜欢
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多