Android handler-每 10 秒减少音量
Android handler-decraese volume every 10 second
我想创建一个按钮,单击该按钮可每 10 秒调低音量。
我该如何解决?
请帮忙
这是我的代码:
public class MainActivity extends Activity {
public AudioManager myAudioManager;
final Handler handler = new Handler();
private Button start;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button) findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
myAudioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
}
}, 10000);
}
});
}
很遗憾,我的应用程序已停止
这里是logCat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.myapp.MainActivity.run(MainActivity.java:36)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
您错过了获取 AudioManager 的引用
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
我想创建一个按钮,单击该按钮可每 10 秒调低音量。
我该如何解决? 请帮忙
这是我的代码:
public class MainActivity extends Activity {
public AudioManager myAudioManager;
final Handler handler = new Handler();
private Button start;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button) findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
myAudioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
}
}, 10000);
}
});
}
很遗憾,我的应用程序已停止
这里是logCat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.myapp.MainActivity.run(MainActivity.java:36)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
您错过了获取 AudioManager 的引用
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);