getApplicationContext()方法获取错误

时间:2017-08-14 16:23:31

标签: java android

我是Android初学者,制作一个简单的Service示例。

但在单个代码中getApplicationContext()方法的行为有所不同,请检查MainActivity的评论。

MainActivity.java

package com.avisingh.servicetest;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

    final Button alertButton = (Button)findViewById(R.id.alert_btn);

    alertButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //If i placing here getApplicationContext() method then getting error;
            builder.setTitle("Warning");
            builder.setMessage("Are you sure to open media played in this app?");

            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(getApplicationContext(),PlayerActivity.class)); // here getApplicationContext() and MainActivity.this both working
                }
            });

            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog alertDialog = builder.create();
            alertDialog.show(); //getting error here.
        }
    });
 }
}

PlayerActivity.java

package com.avisingh.servicetest;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;


public class PlayerActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player_activity);

    final Button startBtn = (Button)findViewById(R.id.start_btn);
    final Button stopBtn = (Button)findViewById(R.id.stop_btn);

    startBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(getApplicationContext(),MyServices.class));
        }
    });

    stopBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(new Intent(getApplicationContext(),MyServices.class));
        }
    });
 }
}

MyServices.java

package com.avisingh.servicetest;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;


public class MyServices extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
    //return null;
    throw  new UnsupportedOperationException("Not implemented");
}

@Override
public void onCreate() {
    super.onCreate();
    mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.one_man);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mediaPlayer.start();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    super.onDestroy();
    mediaPlayer.stop();
 }
}

AndroidManifest

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

<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>
    <activity android:name=".PlayerActivity"/>
    <service android:name=".MyServices"/>
</application>

activity_main

<?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="com.avisingh.servicetest.MainActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/alert_btn"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:id="@+id/alert_btn"/>

</RelativeLayout>

player_activity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="@string/start_btn"
    android:id="@+id/start_btn"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="@string/stop_btn"
    android:id="@+id/stop_btn"/>

</RelativeLayout>

错误:

08-14 14:17:58.916 6874-6874/com.avisingh.servicetest E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.avisingh.servicetest, PID: 6874
                                                                    java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                        at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                                        at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                                        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                                        at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
                                                                        at android.support.v7.app.AlertController.installContent(AlertController.java:225)
                                                                        at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                        at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
                                                                        at android.app.Dialog.show(Dialog.java:274)
                                                                        at com.avisingh.servicetest.MainActivity$1.onClick(MainActivity.java:42)
                                                                        at android.view.View.performClick(View.java:4759)
                                                                        at android.view.View$PerformClick.run(View.java:19770)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5247)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

1 个答案:

答案 0 :(得分:4)

//If i placing here getApplicationContext() method then getting error

正确。这是因为Application对象对主题一无所知,而您的对话框需要基于Theme.AppCompat的主题。始终使用Activity上下文创建对话框。

您可能希望阅读Dave Smith's awesome blog post on the uses of different types of Context object了解更多信息。