項(xiàng)目需求:
點(diǎn)擊圖標(biāo)有界面,自動運(yùn)行或者開發(fā)點(diǎn)擊運(yùn)行項(xiàng)目無界面
這個需求困擾了我很久椅野,2天多吧 后來換了一個思路就實(shí)現(xiàn)了
效果圖:
2222222.gif
就是弄個全局變量,在就是開啟一個服務(wù)里去賦值就行...
我之前想的是怎么獲取APP圖標(biāo)籍胯,在去監(jiān)聽這個圖標(biāo)的事件竟闪,在給全局變量賦值,之后再依據(jù)全局變量去判斷杖狼。
image.png
代碼如下
package com.test.testdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!Config.runFlag){
Log.i("TAG", "自動或者點(diǎn)擊運(yùn)行無界面---- ");
Intent intent = new Intent(this, TestService.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
finish();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點(diǎn)擊圖標(biāo)啟動你才會看見我"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.test.testdemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.Nullable;
/**
* @auther eerdunsang
* @date 2021/3/8
* @time 14:20.
*/
public class TestService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Config.runFlag = true;
}
@Override
public void onDestroy() {
super.onDestroy();
Config.runFlag = false;
}
}
package com.test.testdemo;
/**
* @auther eerdunsang
* @date 2021/3/8
* @time 14:21.
*/
public class Config {
public static boolean runFlag = false;
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.testdemo">
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TestService"/>
</application>
</manifest>