簡體   English   中英

¿ 如何在后台啟動我的應用程序或活動?

[英]¿How can i launch my app or an activity in background?

當我的應用程序在后台時,如何啟動活動? 我的意思是,當它沒有被破壞時? 我已經嘗試過 IntentService 並且什么都沒有,我只想制作一個 StartActivity 來在后台啟動我的 MainActivity。

右擊項目,Select New >> Service >> Service 並在 MyServices.java 中添加以下內容

public class MyService extends Service {
   public MyService() {
   }
   @Override
   public int onStartCommand(Intent intent, int flags, int startId){
      onTaskRemoved(intent);
      Toast.makeText(getApplicationContext(),"This is a Service running in Background",
      Toast.LENGTH_SHORT).show();
      return START_STICKY;
   }
   @Override
   public IBinder onBind(Intent intent) {
      // TODO: Return the communication channel to the service.
      throw new UnsupportedOperationException("Not yet implemented");
   }
   @Override
   public void onTaskRemoved(Intent rootIntent) {
      Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
      restartServiceIntent.setPackage(getPackageName());
      startService(restartServiceIntent);
      super.onTaskRemoved(rootIntent);
   }
}

將以下代碼添加到 res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/button"
      android:text="Click here"
      android:textStyle="bold"
      android:textSize="16sp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true" />
</RelativeLayout>

將以下代碼添加到 src/MainActivity.java

public class MainActivity extends AppCompatActivity {
   Button button;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            startService(new Intent(getApplicationContext(),MyService.class));
         }
      });
   }
}

將以下代碼添加到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <service
         android:name=".MyService"
         android:enabled="true"
         android:exported="true"></service>
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試運行您的應用程序。
單擊單擊此處按鈕以啟動后台服務。

您的服務需要是前台服務。 這里是如何。

首先在您的Manifest.xml文件中。 請求許可

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

......

<!-- Your Service-->
<service
  android:name=".MyService"
  android:enabled="true"
  android:exported="true"
  android:permission="android.permission.FOREGROUND_SERVICE"/>

使用以下命令啟動您的服務: startForegroundService(Intent(this, MyService::class.java))

然后在您的服務中顯示前台通知(通常在 onStartCommand 中):

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val ncCompat = NotificationChannelCompat.Builder("your.own.id.here", NotificationManagerCompat.IMPORTANCE_DEFAULT).setName("Important").build()

NotificationManagerCompat.from(baseContext).createNotificationChannel(ncCompat)
startForeground("your.notification.id.goes.here".hashCode(), NotificationCompat.Builder(baseContext, nmCompat.id).setContentTitle("My Foreground Service").setContentText("Running Service").build())


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

然后你可以開始一個活動(例如:見下文)

val intent = Intent(application, MainActivity2::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
intent.addFlags(Intent.FLAG_FROM_BACKGROUND)
startActivity(intent)

Android 可能會抱怨您的活動需要從Theme.AppCompat繼承主題,並且您在加載 xml 布局時也可能遇到困難。

我相信你可以解決這些問題。 除此之外,你對 go 很好。 另請注意,我僅在 Android 10 及以下版本上對其進行了測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM