不可转换的类型;无法投放android.app.Application错误?

时间:2019-07-04 16:29:11

标签: android

我的目标是检测用户何时进入后台。我使用了this answer to get me setup

但是,当我用他的类名(“ MainActivity”)替换他代码中有“ MyApplication” 的位置时。我会出现不可转换的类型错误。

我是android studio的新手,不知道如何解决此问题。任何帮助将不胜感激。

主要活动代码:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {



    private Timer mActivityTransitionTimer;
    private TimerTask mActivityTransitionTimerTask;
    public boolean wasInBackground;
    private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000;

    @Override
    public void onResume()
    {
        super.onResume();

        MainActivity myApp = (MainActivity)this.getApplication();
        if (myApp.wasInBackground)
        {
            //Do specific came-here-from-background code
        }

        myApp.stopActivityTransitionTimer();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        ((MainActivity)this.getApplication()).startActivityTransitionTimer();
    }

   public void startActivityTransitionTimer() {
        this.mActivityTransitionTimer = new Timer();
        this.mActivityTransitionTimerTask = new TimerTask() {
            public void run() {
                MainActivity.this.wasInBackground = true;
            }
        };

        this.mActivityTransitionTimer.schedule(mActivityTransitionTimerTask,
                MAX_ACTIVITY_TRANSITION_TIME_MS);
    }

    public void stopActivityTransitionTimer() {
        if (this.mActivityTransitionTimerTask != null) {
            this.mActivityTransitionTimerTask.cancel();
        }

        if (this.mActivityTransitionTimer != null) {
            this.mActivityTransitionTimer.cancel();
        }

        this.wasInBackground = false;
    }

}

错误位置

编辑:下面的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jstudios.cars">


    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Cars"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashActivity"
            android:label="@string/app_name"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="CarsApp"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

</manifest>

意图过滤器用于初始屏幕。

编辑:@Modi Harsh

LifeCycleObserverClassCode:

enter image description here

LifeCycleObserver目录:

enter image description here

MainActivity中的代码输入:

enter image description here

MainActivityJava中的编辑2错误:

enter image description here

在MyLifeCycleObserverClass中编辑2错误:

enter image description here

3 个答案:

答案 0 :(得分:2)

您需要创建一个扩展Application的类-这与您的Main活动不同。 The docs describe it as

  

用于维护全局应用程序状态的基类。您可以提供   您可以通过创建子类并指定   此子类的完全限定名称为“ android:name”属性   在您的AndroidManifest.xml标签中。应用程序   类或您的Application类的子类被实例化   在您的应用程序/软件包的处理过程之前,在任何其他类之前   已创建。

它看起来像这样:

## Build a node application
from node:8.11.1
WORKDIR /app

## Copy all the files
COPY . ./sortier

## Build run and test
RUN  cd ./sortier \
  && npm install --unsafe-perm \
  && npm run test \
  && cd .. \
## Run react-redux-typescript-guide/playground test
  && pwd \
  && git clone https://github.com/piotrwitek/react-redux-typescript-guide  \
  && cd react-redux-typescript-guide/playground \
  && npm install --unsafe-perm \
  && echo "{ isHelpMode: true }" > .sortierrc \
  && cd ../../sortier \
  && npm run start -- "../react-redux-typescript-guide/playground/src/**/*.ts" \
  && npm run start -- "../react-redux-typescript-guide/playground/src/**/*.tsx" \
  && cd ../react-redux-typescript-guide/playground \
  && npm run build \
  && cd ../.. \
## Run prettier test
  && pwd \
  && git clone https://github.com/prettier/prettier \
  && cd prettier \
  && npm install --unsafe-perm \
  && echo "{ isHelpMode: true }" > .sortierrc \
  && cd .. \
  && npm run start -- "prettier/src/**/*.js" \
  && cd prettier \
  && npm run build \
  && npm run test \
  && cd ..

在Manifest.xml文件中,您将需要以下内容来向Android告知您的自定义应用程序类:

public class MyApplication extends Application {

}

我认为您需要将<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="your.package.name"> .... <application android:name=".MyApplication" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true"> </manifest> startActivityTransitionTimer方法移至新的MyApplication类。

然后,您的stopActivityTransitionTimeronPause方法应该可以使用此方法:

onResume

PS,您可以随心所欲地致电(MyApplication) this.getApplication() 类。

PPS可能值得一读有关fundamentals of Android components here

答案 1 :(得分:1)

可以通过Android Architecture Component: LifeCycle

实现

添加build.gradle

LifecycleObserver

创建您的Observer类,并使用class MyLifeCycleObserver : LifecycleObserver { private var lifeCycleObserverCallback: LifeCycleObserverCallback? = null fun registerCallback(lifeCycleObserverCallback: LifeCycleObserverCallback) { this.lifeCycleObserverCallback = lifeCycleObserverCallback } @OnLifecycleEvent(Lifecycle.Event.ON_START) private fun onAppForeground() { lifeCycleObserverCallback?.onForeground() } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) private fun onAppBackground() { lifeCycleObserverCallback?.onBackground() } public interface LifeCycleObserverCallback { fun onForeground() fun onBackground() } }

实施

科特琳:

public class MyLifeCycleObserver implements LifecycleObserver {

    private LifeCycleObserverCallback lifeCycleObserverCallback;

    public void registerCallback(LifeCycleObserverCallback lifeCycleObserverCallback) {
        this.lifeCycleObserverCallback = lifeCycleObserverCallback;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForeground() {
        lifeCycleObserverCallback.onForeground();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackground() {
        lifeCycleObserverCallback.onBackground();
    }

    public interface LifeCycleObserverCallback{
        void onForeground();
        void onBackground();
    }
}

Java:

onCreate

val observer = MyLifeCycleObserver() lifecycle.addObserver(observer) observer.registerCallback(this) 的活动中添加以下几行

科特琳:

MyLifeCycleObserver observer = new MyLifeCycleObserver();
getLifecycle().addObserver(observer);
observer.registerCallback(this);

Java:

LifeCycleObserverCallback

之后,在您的Activity中实现override fun onForeground() { // do whatever you want (App in Foreground) } override fun onBackground() { // do whatever you want (App in Background) } 侦听器并覆盖这两种方法

科特琳:

@Override
public void onForeground() {
//    do whatever you want (App in Foreground)
}

@Override
public void onBackground() {
//    do whatever you want (App in Background)
}

Java:

{{1}}

完成:)

答案 2 :(得分:-2)

如果要使用该答案和强制转换,则需要将Application扩展到MainActivity类中。