从广播接收器启动服务导致应用程序崩溃

时间:2016-09-17 09:02:17

标签: android service bluetooth broadcastreceiver

我正在尝试启动一个简单的service,只有在收到toastsbluetooth on的系统广播时才显示off。 我的broadcastReceiver类:

public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub

        String bluth=arg1.getAction();
        if(bluth.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
            if(arg1.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
                    == BluetoothAdapter.STATE_ON){
                SharedPreferences sp=arg0.getSharedPreferences(prefs,
                        Context.MODE_PRIVATE);
                Editor ed=sp.edit();
                ed.putInt(count, counter);
                ed.commit();
                counter++;
                Toast.makeText(arg0, "Bluetooth on  "+sp.getInt(count,0), Toast.LENGTH_LONG).show();
                i=new Intent(arg0,NotifyTimer.class);
                arg0.startService(i);
                //i=new Intent(arg0,Indicators.class);
                //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //arg0.startActivity(i);
                //Indicators.on.setVisibility(View.VISIBLE);
            }else if(arg1.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
                    == BluetoothAdapter.STATE_OFF){
                arg0.stopService(i);

            }else if(arg1.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
                    == BluetoothAdapter.STATE_TURNING_OFF){

            }else if(arg1.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
                    == BluetoothAdapter.STATE_TURNING_ON){

            }
        }

我的服务类代码:

public class NotifyTimer extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(getBaseContext(), "Service created", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(getBaseContext(), "Service destroyed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        /*NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(getBaseContext());
        mBuilder.setColor(Color.RED);
        mBuilder.setContentTitle("Bluetooth opened ");
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);

         mNotificationManager.notify(0, mBuilder.build()); 
        mBuilder.setAutoCancel(true);
    */
        Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

}

现在每当我运行我的代码时,我都看不到服务 toast,每当我关闭蓝牙时,应用程序都会崩溃!

有人能找出原因吗?

0 个答案:

没有答案