android:服务无法启动重启设备

时间:2014-10-14 12:39:54

标签: android service broadcastreceiver alarmmanager

我有一个应用程序,在一段时间间隔后通过短信发送gps坐标。我想让它在重启设备后自动运行。我尝试了不同的解决方案,但我仍然不知道如何在服务中调用方法。请告诉我我的代码有什么问题。

主要活动代码

public class MainActivity extends Activity {

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

    startLocationTracking();

}

private void startLocationTracking()
{
    AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
    Intent alarmintent1=new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

    try {
        am.cancel(sender1);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("exjfkd"+e);
    }

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND,5);

    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10, sender1);
    System.out.println("set timer");
}

} broadcastReceiver的代码

long time = 10 * 1000; 
long distance = 10; 

@SuppressLint("NewApi") 
@Override
public void onReceive(final Context context, Intent intent) {

    System.out.println("alarm receiver....");
    Intent service = new Intent(context, MyService.class);
    context.startService(service);

    LocationManager locationManager = (LocationManager)context
            .getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);

    locationManager.requestLocationUpdates(provider, time,
            distance, locationListener);


    Location location = locationManager.getLastKnownLocation(provider);

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String device_id = tm.getDeviceId();  // returns IMEI number 

    String phoneNo = "+95984690850";

    String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude() + " Device Id: " + device_id;

    try {
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(phoneNo, null, Text, null, null);
    Log.i("Send SMS", "");

    Toast.makeText(context, "message sent", Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
    Toast.makeText(context, "SMS faild, please try again.",
    Toast.LENGTH_LONG).show();
    e.printStackTrace();
 } 
    this.abortBroadcast();

}

 LocationListener locationListener = new LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
};

}

服务类代码

public class MyService extends Service{

 private NotificationManager mManager;

 private final IBinder mBinder = new MyBinder();
    @Override
    public IBinder onBind( Intent arg0 )
    {
        return mBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
       Log.d( "oncreated", "oncreated" );
    }

    @Override
    public void onDestroy() {

    }

    public class MyBinder extends Binder {
        MyService getService() {
        return MyService.this;
      }
    }

} 清单文件

 <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="com.example.locationupdates.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


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

    <receiver 
      android:name="com.example.locationupdates.AlarmReceiver">
      <intent-filter android:priority="100">
      <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
      <action android:name="android.intent.action.BOOT_COMPLETED" />

     </intent-filter>
    </receiver>

  </application>

1 个答案:

答案 0 :(得分:0)

当动作等于启动时,在AlarmReceiver中启动闹钟,如下所示

public void onReceive(Context context, Intent intent) {   
    if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
   //Start your alarm here by using context
             AlarmManager am=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
    Intent alarmintent1=new Intent(context, AlarmReceiver.class);
    PendingIntent sender1=PendingIntent.getBroadcast(context, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

    try {
        am.cancel(sender1);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("exjfkd"+e);
    }

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND,5);

    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10, sender1);
    System.out.println("set timer");
  }