life cycle , app reopen by itself - java

after understanding life cycle and try code onDestroy() to the app it still the same problem that app starting by itself , if i try to close the app in any way exp by multi-tasking it starting again by it self i want to make it don't start again after closing it that code for
MainActivity.java
package com.webcraftbd.radio;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
static String radioTitle = "Radio 16Bar";
static String radioStreamURL = "http://s9.voscast.com:8724";
Button playButton;
Button pauseButton;
Button stopButton;
TextView statusTextView, bufferValueTextView;
NotificationCompat.Builder notifyBuilder;
private RadioUpdateReceiver radioUpdateReceiver;
private RadioService radioServiceBinder;
//Notification
private static final int NOTIFY_ME_ID=12345;
private NotificationManager notifyMgr=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView titleTextView = (TextView) this.findViewById(R.id.titleTextView);
titleTextView.setText(radioTitle);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
statusTextView = (TextView) this.findViewById(R.id.StatusDisplayTextView);
notifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
// Bind to the service
Intent bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, RadioService.class));
}
public void onClickPlayButton(View view) {
radioServiceBinder.play();
}
public void onClickPauseButton(View view) {
radioServiceBinder.pause();
}
public void onClickStopButton(View view) {
radioServiceBinder.stop();
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null) radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_END));
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
showNotification();
}
else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
clearNotification();
}
else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Rady");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_START)) {
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_END)) {
updateStatus("Playing");
}
else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
showNotification();
updateStatus("Playing");
}
else if(intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Paused");
}
else if(intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
clearNotification();
}
else if(intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
}
else if(intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Error");
}
}
}
public void updateStatus(String status) {
try {
if(notifyBuilder!=null && notifyMgr!=null) {
notifyBuilder.setContentText(status).setWhen(0);
notifyMgr.notify(NOTIFY_ME_ID,notifyBuilder.build());
}
statusTextView.setText(status);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void showNotification() {
notifyBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(radioTitle).setContentText("");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notifyBuilder.setContentIntent(resultPendingIntent);
notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
public void clearNotification() {
notifyMgr.cancel(NOTIFY_ME_ID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioServiceBinder = ((RadioService.RadioBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
radioServiceBinder = null;
}
};
}

Related

How to make BLE scan and MQTT publish work in background Android Studio Java

I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.

Attempt to invoke virtual method 'void android.view.View.setAlpha(float) [duplicate]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an Android app. This app has 12 activities, the first activity is the Splash Screen and sec activity is the intropage and 3rd activity is main and etc When I run the app, it doesn't enter the main activity and the app closes. The error is as follows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at com.github.hujiaweibujidao.wava.BaseViewAnimator.reset(BaseViewAnimator.java:78)
at com.github.hujiaweibujidao.wava.BaseViewAnimator.start(BaseViewAnimator.java:55)
at com.github.hujiaweibujidao.wava.YoYo$Builder.start(YoYo.java:128)
at com.github.hujiaweibujidao.wava.YoYo$Builder.playOn(YoYo.java:115)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:108)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Thank you for your answers, but the solutions you gave me did not help. I checked, but it still gave me the same error. I put three-activated codes for you. Can you help me, please?
this my main activity java code:
package com.example.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.akshay.library.CurveBottomBar;
import com.github.hujiaweibujidao.wava.Techniques;
import com.github.hujiaweibujidao.wava.YoYo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mxn.soul.flowingdrawer_core.ElasticDrawer;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
public class MainActivity extends AppCompatActivity {
CurveBottomBar cbb;
FlowingDrawer mDrawer;
ImageView img_icon,imgtest,img_music,img_night,img_main,img_setting;
TextView txt;
String patch;
boolean read=false,music=true,night_mode;
Button btn_fehrest,btn_last_story,btn_fav;
SharedPreferences sharedP;
LinearLayout lin_main;
Toast exit;
boolean show_intropage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbb = findViewById(R.id.cbb);
mDrawer = findViewById(R.id.drawerlayout);
img_icon = findViewById(R.id.img_icon);
imgtest = findViewById(R.id.imgtest);
txt = findViewById(R.id.txt);
btn_fehrest = findViewById(R.id.btn_fehrest);
img_music = findViewById(R.id.img_music);
lin_main = findViewById(R.id.lin_main);
img_night = findViewById(R.id.img_night);
img_main = findViewById(R.id.img_main);
btn_last_story = findViewById(R.id.btn_last_story);
btn_fav = findViewById(R.id.btn_fav);
img_setting = findViewById(R.id.img_setting);
cbb.inflateMenu(R.menu.menu_scrolling);
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);
cbb.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.img_setting:
// kary ke mikhaym anjam bedim
break;
case R.id.img_music:
//
break;
}
return false;
}
});
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fehrest);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_last_story);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fav);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_music);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_setting);
get_night();
permission();
//createFile();
if (show_intropage){
taptarget();
}
img_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openMenu(true);
}
});
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
mDrawer.setBackgroundColor(Color.WHITE);
mDrawer.setOnDrawerStateChangeListener(new ElasticDrawer.OnDrawerStateChangeListener() {
#Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == ElasticDrawer.STATE_CLOSED) {
Log.i("MainActivity", "Drawer STATE_CLOSED");
}
}
#Override
public void onDrawerSlide(float openRatio, int offsetPixels) {
Log.i("MainActivity", "openRatio=" + openRatio + " ,offsetPixels=" + offsetPixels);
}
});
}
public void createFile(){
try {
patch = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mbook/";
File mfile = new File(patch);
if (!mfile.exists()) {
mfile.mkdir();
mfile.createNewFile();
CopyDB(getBaseContext().getAssets().open("Mbook.db"), new FileOutputStream(patch+"/Mbook.db"));
//Toast.makeText(this, patch+"", Toast.LENGTH_LONG).show();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void CopyDB (InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int file_length;
while ((file_length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,file_length);
}
inputStream.close();
outputStream.close();
}
public void fehrest_intent(View view) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(800).playOn(btn_fehrest);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fehrest");
startActivity(intent);
}
},1500);
}
private void permission(){
Dexter.withContext(MainActivity.this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
createFile();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response !=null && response.isPermanentlyDenied()){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
}
Toast.makeText(MainActivity.this, "جهت استفاده از برنامه دادن اجازه دسترسی ضروریست", Toast.LENGTH_SHORT).show();
alert();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, final PermissionToken token) {
alert();
}
}).check();
}
public void alert(){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setTitle("توجه");
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست لطفا درقسمت تنظیمات اجازه دسترسی را فعال کنید");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
Hoshdar.create().show();
}
public void fav_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_fav);
mDrawer.closeMenu(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fav");
intent.putExtra("activity","main");
startActivity(intent);
}
},1500);
}
public void text_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_last_story);
if (read){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent_movies = new Intent(getBaseContext(), Text_activity.class);
intent_movies.putExtra("activity","main");
startActivity(intent_movies);
}
},1500);
}else {
Toast.makeText(this, "هنوز هیچ داستانی مطالعه نکردید!", Toast.LENGTH_SHORT).show();
}
}
public void setting_intent(MenuItem item) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(600).playOn(img_setting);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,Setting.class));
}
},1500);
}
public void set_music(MenuItem item) {
YoYo.with(Techniques.Pulse).duration(600).playOn(img_music);
if (music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
music=false;
sharedP.edit().putBoolean(Items.MUSIC, false).apply();
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
music=true;
sharedP.edit().putBoolean(Items.MUSIC, true).apply();
}
}
public void get_night(){
music = sharedP.getBoolean(Items.MUSIC,true);
night_mode = sharedP.getBoolean(Items.NIGHT_MODE,false);
read = sharedP.getBoolean(Items.READ,false);
if (night_mode){
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
}else {
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
}
if (!music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
}
}
public void set_night(View view){
YoYo.with(Techniques.RotateIn).duration(800).playOn(img_night);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (night_mode){
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
sharedP.edit().putBoolean(Items.NIGHT_MODE, false).apply();
night_mode=false;
}else {
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
sharedP.edit().putBoolean(Items.NIGHT_MODE, true).apply();
night_mode=true;
}
}
},800);
}
#Override
protected void onResume() {
super.onResume();
get_night();
}
#Override
protected void onDestroy() {
stopService(new Intent(MainActivity.this,PlayMusic.class));
super.onDestroy();
}
public void finish(View view) {
mDrawer.closeMenu(true);
finish();
}
#SuppressLint("ResourceAsColor")
private void taptarget(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_night)
.setPrimaryText("فعال کردن حالت شب")
.setSecondaryText("با زدن این دکمه میتوانید حالت مطالعه در شب را فعال یا غیر فعال کنید")
//.setPrimaryTextColour(Color.parseColor("#13dc74"))
// .setSecondaryTextColour(Color.parseColor("#13dc74"))
.setFocalColour(R.color.mycolorGray)
.setBackButtonDismissEnabled(false)
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED|| state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "اولی", Toast.LENGTH_SHORT).show();
txt_target();
}
}
})
.show();
}
private void txt_target(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_icon)
.setFocalColour(R.color.mycolorGray)
.setPrimaryText("منوی کشویی")
.setSecondaryText("با زدن این دکمه منوی کشویی برنامه باز خواهد شد که شامل آیتم های مختلفی می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target3();
}
}
})
.show();
}
private void target3(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_music)
.setPrimaryText("فعال/غیرفعال موزیک")
.setSecondaryText("با زدن این دکمه میتوانید موزیک پس زمینه حین مطالعه را پخش یا قطع کنید")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target4();
}
}
})
.show();
}
private void target4(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_setting)
.setPrimaryText("تنظیمات")
.setSecondaryText("با زدن این دکمه بخش تنظیمات باز خواهد شد که شامل تغییر فونت متن ، سایز متن و ... می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
sharedP.edit().putBoolean(Items.INTROPAGE, false).apply();
}
}
})
.show();
}
#Override
public void onBackPressed() {
if (!(exit ==null)){
super.onBackPressed();
//MainActivity.this.finish();
}else {
exit = Toast.makeText(this,"برای خروج دوباره بزنید",Toast.LENGTH_LONG);
exit.show();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit= null;
}
},3000);
}
}
this my main activity xml code:
Splash Screen Activity Run enters Intro Page. After clicking the reject or complete button, the program will not enter the activity menu and the program will close.
Please follow the below options. Hope your problem will be solved.
1) Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"
<activity
android:name=".MainActivity" >
</activity>
2) Clean and rebuilt the project and Hope it will work.
You forgot find view btn_last_story add it to onCreate
btn_last_story = findViewById(R.id.btn_last_story);

How to remove the button after purchase

Please help!!!
I am creating a screen capture application and the problem is that after clicking the PRO button and after the purchase, the ads and the button do not hide.
I am trying to remove a button and ads using layout changes:
setContentView (R.layout.main_pro)
the code:
IabHelper.OnIabPurchaseFinishedListener () {
#Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1000;
private int mScreenDensity;
File file;
private Context context;
private ShareActionProvider mShareActionProvider;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
static final String SKU_REMOVE_ADS = "android.test.purchased";
static final int RC_REQUEST = 10111;
private MediaProjectionCallback mMediaProjectionCallback;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSION_KEY = 1;
boolean isRecording = false;
private FloatingActionButton rec;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Intent intent;
private Activity activity;
private boolean URL_TO_SHARE;
private ImageView wm;
private NotificationManagerCompat notificationManager;
private String title;
private String message;
private InterstitialAd mInterstitialAd;
private String testDeviceId;
AdRequest adRequest;
private AdView adView;
IabHelper mHelper;
String base64EncodedPublicKey = "PublicKey";
Boolean isAdsDisabled = false;
String payload = "Upgrade PRO";
private Inventory i;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
private static boolean isWidget = false;
private static Context appContext;
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView pro = (ImageView) findViewById(R.id.buy);
final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
pro.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
purchaseRemoveAds();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Handler handler = new Handler();
final Timer timer = new Timer();
final TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 120000);
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
AdRequest adRequestInterstitial = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = new AdSize(320, 50);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
if (!Service.hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
}
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
rec = (FloatingActionButton) findViewById(R.id.rec);
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onToggleScreenShare();
}
});
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(false);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
return;
}
if (mHelper == null)
return;
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
queryPurchased();
IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView(R.layout.main_pro);
removeAds();
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
}
private void queryPurchased() {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else{
// does the user have the premium upgrade?
isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
// update UI accordingly
}
}
};
}
public void purchaseRemoveAds() {
try {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
} catch (Exception e) {
e.printStackTrace();
mHelper.flagEndAsync();
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.error)
.setMessage(R.string.error_play_store)
.setPositiveButton("OK", null)
.show();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: "
+ purchase);
if (mHelper == null)
return;
if (result.isFailure()) {
return;
}
if (!verifyDeveloperPayload(purchase)) {
return;
}
if (isAdsDisabled == true){
setContentView(R.layout.main_pro);
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
removeAds();
}
}
};
}
private void removeAds() {
adView.setEnabled(false);
adView.setVisibility(View.INVISIBLE);
}
public void onToggleScreenShare() {
if (!isRecording) {
Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
startService();
initRecorder();
shareScreen();
} else {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ads not loaded!");
}
Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
stopService();
mMediaRecorder.stop();
mMediaRecorder.reset();
stopScreenSharing();
}
}
private void shareScreen() {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(16); // 30
mMediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private File initFile() {
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator + "ScreenRecorder");
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG,
R.string.error_folder
+ dir.getAbsolutePath());
file = null;
} else {
file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return file;
}
private void stopScreenSharing() {
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
destroyMediaProjection();
isRecording = false;
}
private void destroyMediaProjection() {
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
Log.i(TAG, "MediaProjection Stopped");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
Log.e(TAG, "Unknown request code: " + requestCode);
return;
}
if (resultCode != RESULT_OK) {
Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
isRecording = false;
return;
}
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
} else
Log.d(TAG, "onActivityResult handled by IABUtil.");
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_KEY: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
onToggleScreenShare();
} else {
isRecording = false;
Snackbar.make(findViewById(android.R.id.content), R.string.message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
private class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
if (isRecording) {
isRecording = false;
mMediaRecorder.stop();
mMediaRecorder.reset();
}
mMediaProjection = null;
stopScreenSharing();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (mHelper != null)
try {
mHelper.dispose();
mHelper = null;
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
if (adView != null) {
adView.destroy();
}
super.onDestroy();
destroyMediaProjection();
}
private void about() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.about);
builder1.setMessage(R.string.description);
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#SuppressLint("ResourceType")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
about();
return true;
case R.id.share:
shareApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
#SuppressLint({"StringFormatInvalid", "LocalSuppress"})
String extraText = getString(R.string.share_desc, getString(R.string.link));
intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
public void startService() {
Intent serviceIntent = new Intent(this, Background.class);
serviceIntent.putExtra("inputExtra", "Notification");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, Background.class);
stopService(serviceIntent);
}
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
return true;
}
}
And it looks like this:
What am I doing wrong? How can I fix this?
Thanks for any help!

Why is musicSrv null?

Server connection:
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
Log.i("Test",binder.getService().toString());
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
Where I get an error:
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
Log.d("Item clicked","Song picked"+Integer.parseInt(view.getTag().toString()));
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
MusicService.java
package com.musicplayer;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.IBinder;
import java.util.ArrayList;
import android.content.ContentUris;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.PowerManager;
import android.util.Log;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import com.lyricscloud.R;
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
private String songTitle="";
private static final int NOTIFY_ID=1;
private final IBinder musicBind = new MusicBinder();
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
public void initMusicPlayer(){
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void onCreate(){
super.onCreate();
//initialize position
songPosn=0;
//create Player
player = new MediaPlayer();
initMusicPlayer();
}
#Override
public void onDestroy() {
stopForeground(true);
}
public void playSong(){
player.reset();
Song playSong = songs.get(songPosn);
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
public void onCompletion(MediaPlayer mp) {
if(player.getCurrentPosition() <= 0){
mp.reset();
playNext();
}
}
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
public void playPrev(){
songPosn--;
if(songPosn <= 0) songPosn=songs.size()-1;
playSong();
}
public void playNext(){
songPosn++;
if(songPosn >= songs.size()) songPosn=0;
playSong();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
public void setSong(int songIndex){
songPosn=songIndex;
Log.d("Service", ""+songIndex);
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Intent notIntent = new Intent(this, MusicPlayer_Songs.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing");
builder.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
}
The error
08-04 22:50:31.796 23825-23825/com.lyricscloud.dev E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lyricscloud.dev, PID: 23825
java.lang.NullPointerException
at com.musicplayer.MusicPlayer_Songs.songPicked(MusicPlayer_Songs.java:47)
at com.musicplayer.MusicPlayer_Songs$3.onItemClick(MusicPlayer_Songs.java:117)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1478)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3480)
at android.widget.AbsListView$3.run(AbsListView.java:4823)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
I'm not sure whats causing it, I need help please, the app is a musicplayer and whenever I click a list item it gives me that error
onStart() callback:
public void onStart() {
super.onStart();
if(playIntent==null){
Log.i("Play Intent","Is null");
playIntent = new Intent(c, MusicService.class);
//c is rootView.getContext() from onCreateView()
c.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
c.startService(playIntent);
}
}

Facebook Login doesn't work, what did I forget?

Ok,
I'm doing this for 4 straight hours. And the facebook Login still doesn't work. The session state is always OPENING. ALWAYS. onActivityResult NEVER gets called. The key in the developer console is correct, the starting class is correct, and this is my code
package XXXXX
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import ua.org.zasadnyy.zvalidations.Field;
import ua.org.zasadnyy.zvalidations.Form;
import ua.org.zasadnyy.zvalidations.validations.HasMinimumLength;
import ua.org.zasadnyy.zvalidations.validations.IsEmail;
import ua.org.zasadnyy.zvalidations.validations.NotEmpty;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class SplashScreen extends FragmentActivity {
public static String TAG = "SplashScreen";
/**
* LoginActivity
*/
private static final int LOGIN = 0;
private static final int SIGNUP = 1;
private static final int SELECTUSERNAME = 2;
private static final int FRAGMENT_COUNT = SELECTUSERNAME +1;
private boolean isResumed = false;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private MenuItem settings;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/**
* UI Elements
*/
Button btn_signUp;
Button btn_signUpSubmit;
LoginButton btn_facebookAuth;
//Edit Text
EditText edittextEmail;
EditText edittextPassword;
//Form
Form signUpForm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.splash);
FragmentManager fm = getSupportFragmentManager();
fragments[LOGIN] = fm.findFragmentById(R.id.loginFragment);
fragments[SIGNUP] = fm.findFragmentById(R.id.signUpFragment);
fragments[SELECTUSERNAME] = fm.findFragmentById(R.id.selectUserNameFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
btn_signUp = ( Button ) findViewById(R.id.btn_signUpMail);
btn_signUp.setOnClickListener( listener_btn_signUp );
btn_signUpSubmit = (Button) findViewById(R.id.btn_signUpSubmit);
btn_signUpSubmit.setOnClickListener(listener_btn_signUpSubmit);
edittextEmail = (EditText)findViewById(R.id.et_signUpMail);
edittextPassword = (EditText)findViewById(R.id.et_signUpPw);
signUpForm = new Form ( this );
signUpForm.addField(Field.using(edittextEmail).validate(NotEmpty.build(this.getApplicationContext())).validate(IsEmail.build(this.getApplicationContext())));
signUpForm.addField(Field.using(edittextPassword).validate(NotEmpty.build(this.getApplicationContext())).validate(HasMinimumLength.build(this.getApplicationContext(), 8)));
btn_facebookAuth = (LoginButton)findViewById(R.id.login_button);
btn_facebookAuth.setReadPermissions(Arrays.asList("email"));
}
private OnClickListener listener_btn_signUp = new OnClickListener() {
#Override
public void onClick(View v) {
showFragment(SIGNUP, true);
}
};
private OnClickListener listener_btn_signUpSubmit = new OnClickListener() {
#Override
public void onClick(View v) {
if (signUpForm.isValid()) {
Log.i("SignupFragment", "Form is valid");
// User userModel = new User();
// userModel.isFacebookConnected = "0";
// userModel.userEmail = edittextEmail.getText().toString();
// userModel.userPassword = edittextPassword.getText().toString();
// SelectUserNameFragment selectUserNameFragment = new SelectUserNameFragment();
// SelectUserNameFragment.user = userModel;
// getFragmentManager()
// .beginTransaction()
// .replace(android.R.id.content, selectUserNameFragment)
// .addToBackStack("")
// .commit();
} else {
Log.i("SignupFragment", "Form not valid");
}
}
};
private void showFragment(int fragmentIndex, boolean addToBackStack) {
Log.i(TAG, "showFragment");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.i(TAG, "onSessionStateChange");
FragmentManager manager = getSupportFragmentManager();
int backStackSize = manager.getBackStackEntryCount();
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
System.out.println ( state.name() );
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
User userModel = new User();
userModel.facebookId = user.getId();
Map<String, String> where = new HashMap<String, String>();
where.put("where", "WHERE facebookId='" + user.getId() + "'" );
userModel.loadModelFrom(where);
if ( userModel.userData.isEmpty() ) {
userModel.isFacebookConnected = "1";
userModel.userEmail = user.asMap().get("email").toString();
SelectUserNameFragment.user = userModel;
showFragment(SELECTUSERNAME, true);
} else {
Intent intent = new Intent ( getApplicationContext(), DashboardActivity.class );
intent.putExtra("User", userModel);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
// showFragment(DASHBOARD, false);
} else if (state.isClosed()) {
showFragment(LOGIN, false);
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Log.i(TAG, "onResumeFragments");
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Intent intent = new Intent ( this, DashboardActivity.class );
intent.putExtra("Session", session);
startActivity(intent);
} else {
showFragment(LOGIN, false);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
uiHelper.onResume();
isResumed = true;
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "onPause");
uiHelper.onPause();
isResumed = false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
uiHelper.onSaveInstanceState(outState);
}
}
What did I forget?
Apparently it is not allowed to have
android:noHistory="true" in your manifest. I removed it and now it works.

Categories