如何在显示应用程序屏幕的电源开启后在后台运行应用程序?

时间:2017-10-14 05:56:29

标签: android startup

使用此How do I start my app on startup?后期运行应用程序设计成功时

但是当设计运行时,显示我的main_activity

我想在后台运行应用程序(因为我在后台调用带有计时器的检查服务器的排球请求)

我的manifest.xml:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
   <receiver
        android:enabled="true"
        android:exported="true"
        android:name="other_class.CLASS_START_UP"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </receiver>

我的班级start_up:

public class CLASS_START_UP extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}
}

我使用这篇帖子Run volley request every 5 minutes in background android在计时器

中运行截击请求

我的计时器代码是:

 private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {

        get_start_info();

        // Repeat this the same runnable code block again another 2 seconds
        handler.postDelayed(runnableCode, 10000);
    }
};

我的问题是我不想要当设计开启显示主要活动节目给用户(前景)我想只在后台运行

对不起,我的英语不好

1 个答案:

答案 0 :(得分:2)

试试这个

   <receiver android:name=".service.ShutdownReceiver"
        >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.REBOOT"/>
            <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

ShutdownReciver.java

  public class ShutdownReceiver extends BroadcastReceiver
  {
  @Override
  public void onReceive(Context context, Intent intent)
  {
    Log.e("Brodcast Call","####");
    Toast.makeText(context, "service", Toast.LENGTH_SHORT).show();
     //            context.startService(new Intent(context, 
    PowerButtonService.class));
    Intent myIntent = new Intent(context, PowerButtonService.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(myIntent);


}

}